├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .travis.yml ├── LICENSE ├── README.md ├── docs └── _config.yml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── syqu │ │ └── shop │ │ ├── Application.java │ │ ├── StartupData.java │ │ ├── config │ │ ├── WebMvcConfig.java │ │ └── WebSecurityConfig.java │ │ ├── controller │ │ ├── CartController.java │ │ ├── HomeController.java │ │ ├── LoginController.java │ │ ├── ProductController.java │ │ ├── RegisterController.java │ │ └── UserController.java │ │ ├── domain │ │ ├── Category.java │ │ ├── Product.java │ │ └── User.java │ │ ├── repository │ │ ├── CategoryRepository.java │ │ ├── ProductRepository.java │ │ └── UserRepository.java │ │ ├── service │ │ ├── CategoryService.java │ │ ├── ProductService.java │ │ ├── ShoppingCartService.java │ │ ├── UserService.java │ │ └── impl │ │ │ ├── CategoryServiceImpl.java │ │ │ ├── ProductServiceImpl.java │ │ │ ├── ShoppingCartServiceImpl.java │ │ │ ├── UserDetailsServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ └── validator │ │ ├── ProductValidator.java │ │ └── UserValidator.java └── resources │ ├── application.properties │ ├── banner.txt │ ├── i18n │ ├── messages.properties │ └── messages_pl.properties │ ├── static │ ├── css │ │ └── style.css │ ├── favicon.ico │ ├── images │ │ ├── brand.png │ │ ├── brand.svg │ │ ├── cart.png │ │ └── example1.PNG │ └── js │ │ └── lang.js │ └── templates │ ├── about.html │ ├── cart.html │ ├── error │ ├── 403.html │ ├── 404.html │ ├── 500.html │ └── error.html │ ├── fragments │ ├── footer.html │ └── header.html │ ├── home.html │ ├── login.html │ ├── product.html │ ├── register.html │ └── user.html └── test └── java └── com └── syqu └── shop ├── ApplicationTests.java ├── controller ├── CartControllerMvcTests.java ├── ControllersTests.java ├── HomeControllerMvcTests.java └── LoginControllerMvcTests.java ├── creator ├── ProductCreator.java └── UserCreator.java ├── model ├── ProductEntityTests.java └── UserEntityTests.java ├── repository ├── ProductRepositoryTests.java └── UserRepositoryTests.java └── service ├── ProductServiceTests.java ├── ShoppingCartServiceTests.java └── UserServiceTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | nbproject/private/ 21 | build/ 22 | nbbuild/ 23 | dist/ 24 | nbdist/ 25 | .nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk11 4 | before_install: 5 | - chmod +x mvnw 6 | install: 7 | - mvn -N io.takari:maven:wrapper 8 | - ./mvnw install -DskipTests=true -Dmaven.javadoc.skip=true -B -V 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Aleksander Lejawa 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **Spring Boot - Shop Sample** 2 | [![Build Status](https://travis-ci.org/syqu22/spring-boot-shop-sample.svg?branch=master)](https://travis-ci.org/syqu22/spring-boot-shop-sample) 3 | 4 | 5 | 6 | ## Description 7 | 8 | This is my first project using Spring. I wanted to do e-commerce web application to learn Spring. I have used **Spring Boot**, **Spring Security**, **Spring Data JPA** with **H2 database**, for views i have used **Thymeleaf** template and **Bootstrap** CSS framework. 9 | 10 | ## Screenshots 11 | 12 | 13 | 14 | ## Installation 15 | 16 | You can clone this repository and use it localy: 17 | ```sh 18 | $ git clone https://github.com/syqu22/spring-boot-shop-sample.git 19 | ``` 20 | 21 | **Using Maven plugin** 22 | 23 | First you should do clean installation: 24 | ```sh 25 | $ mvn clean install 26 | ``` 27 | You can start application using Spring Boot custom command: 28 | ```sh 29 | $ mvn spring-boot:run 30 | ``` 31 | 32 | **Using Maven plugin and running JAR** 33 | 34 | You can create JAR file using: 35 | ```sh 36 | $ mvn clean package 37 | ``` 38 | and then run it with: 39 | ```sh 40 | $ java -jar target/shop-x.x.x.jar 41 | ``` 42 | 43 | ## Logins 44 | 45 | Initially there are 2 users in memory: 46 | 47 | Login: ```admin``` Password: ```admin``` with **ADMIN** role. 48 | 49 | Login: ```user``` Password: ```user``` with **USER** role. 50 | 51 | ## Roles 52 | 53 | **ADMIN** can add, edit and delete products. 54 | 55 | **USER** can add products to shopping cart and buy them. 56 | 57 | ## Tests 58 | 59 | 60 | You can run tests using: 61 | ```sh 62 | $ mvn test 63 | ``` 64 | 65 | ## License 66 | 67 | Project is based on **MIT License**. You can read about the license here. 68 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.syqu 7 | shop 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | E-shop N3XT 12 | E-commerce shop 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.4.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-security 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-data-jpa 42 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-data-rest 47 | 48 | 49 | 50 | com.h2database 51 | h2 52 | runtime 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-starter-thymeleaf 58 | 59 | 60 | 61 | org.thymeleaf.extras 62 | thymeleaf-extras-springsecurity5 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-devtools 68 | true 69 | runtime 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-actuator 75 | 76 | 77 | 78 | org.springframework.boot 79 | spring-boot-starter-mail 80 | 81 | 82 | 83 | org.springframework.boot 84 | spring-boot-starter-test 85 | test 86 | 87 | 88 | 89 | org.springframework.security 90 | spring-security-test 91 | test 92 | 93 | 94 | 95 | org.webjars 96 | bootstrap 97 | 4.1.0 98 | 99 | 100 | 101 | org.webjars 102 | font-awesome 103 | 5.0.10 104 | 105 | 106 | 107 | org.webjars 108 | jquery 109 | 3.3.1-1 110 | 111 | 112 | org.projectlombok 113 | lombok 114 | true 115 | 116 | 117 | javax.validation 118 | validation-api 119 | 2.0.1.Final 120 | 121 | 122 | junit 123 | junit 124 | 4.13.1 125 | test 126 | 127 | 128 | 129 | 130 | 131 | org.springframework.boot 132 | spring-boot-maven-plugin 133 | 134 | 135 | 136 | org.projectlombok 137 | lombok 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/Application.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | //@EnableJpaRepositories(basePackageClasses = {UserRepository.class, ProductRepository.class}) 8 | public class Application { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(Application.class, args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/StartupData.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop; 2 | 3 | import com.syqu.shop.domain.Category; 4 | import com.syqu.shop.domain.Product; 5 | import com.syqu.shop.repository.CategoryRepository; 6 | import com.syqu.shop.service.ProductService; 7 | import com.syqu.shop.domain.User; 8 | import com.syqu.shop.service.UserService; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.CommandLineRunner; 13 | import org.springframework.stereotype.Component; 14 | 15 | import java.math.BigDecimal; 16 | 17 | @Component 18 | public class StartupData implements CommandLineRunner { 19 | private final UserService userService; 20 | private final ProductService productService; 21 | private final CategoryRepository categoryRepository; 22 | private static final Logger logger = LoggerFactory.getLogger(StartupData.class); 23 | 24 | @Autowired 25 | public StartupData(UserService userService, ProductService productService, CategoryRepository categoryRepository) { 26 | this.userService = userService; 27 | this.productService = productService; 28 | this.categoryRepository = categoryRepository; 29 | } 30 | 31 | @Override 32 | public void run(String... args) { 33 | adminAccount(); 34 | userAccount(); 35 | category(); 36 | exampleProducts(); 37 | } 38 | 39 | private void userAccount(){ 40 | User user = new User(); 41 | 42 | user.setUsername("user"); 43 | user.setPassword("user"); 44 | user.setPasswordConfirm("user"); 45 | user.setGender("Female"); 46 | user.setEmail("user@example.com"); 47 | 48 | userService.save(user); 49 | } 50 | 51 | private void adminAccount(){ 52 | User admin = new User(); 53 | 54 | admin.setUsername("admin"); 55 | admin.setPassword("admin"); 56 | admin.setPasswordConfirm("admin"); 57 | admin.setGender("Male"); 58 | admin.setEmail("admin@example.com"); 59 | 60 | userService.save(admin); 61 | } 62 | 63 | private void category(){ 64 | Category category1 = new Category(); 65 | Category category2 = new Category(); 66 | category1.setId(1); 67 | category1.setCategoryName("Adventure"); 68 | category2.setId(2); 69 | category2.setCategoryName("Novel"); 70 | 71 | categoryRepository.save(category1); 72 | categoryRepository.save(category2); 73 | } 74 | 75 | private void exampleProducts(){ 76 | final String NAME = "Example Name"; 77 | final String IMAGE_URL = "https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX7389458.jpg"; 78 | final String DESCRIPTION = "Example Description"; 79 | final BigDecimal PRICE = BigDecimal.valueOf(22); 80 | 81 | Product product1 = new Product(); 82 | Product product2 = new Product(); 83 | Product product3 = new Product(); 84 | Product product4 = new Product(); 85 | 86 | product1.setName(NAME); 87 | product1.setImageUrl(IMAGE_URL); 88 | product1.setDescription(DESCRIPTION); 89 | product1.setCategory(categoryRepository.findByCategoryName("Adventure")); 90 | product1.setPrice(PRICE); 91 | 92 | product2.setName(NAME); 93 | product2.setImageUrl(IMAGE_URL); 94 | product2.setDescription(DESCRIPTION); 95 | product2.setCategory(categoryRepository.findByCategoryName("Adventure")); 96 | product2.setPrice(PRICE); 97 | 98 | product3.setName(NAME); 99 | product3.setImageUrl(IMAGE_URL); 100 | product3.setDescription(DESCRIPTION); 101 | product3.setCategory(categoryRepository.findByCategoryName("Novel")); 102 | product3.setPrice(PRICE); 103 | 104 | product4.setName(NAME); 105 | product4.setImageUrl(IMAGE_URL); 106 | product4.setDescription(DESCRIPTION); 107 | product4.setCategory(categoryRepository.findByCategoryName("Novel")); 108 | product4.setPrice(PRICE); 109 | 110 | productService.save(product1); 111 | productService.save(product2); 112 | productService.save(product3); 113 | productService.save(product4); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/config/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.config; 2 | 3 | import org.springframework.context.MessageSource; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.support.ReloadableResourceBundleMessageSource; 7 | import org.springframework.web.servlet.LocaleResolver; 8 | import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; 9 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; 12 | import org.springframework.web.servlet.i18n.SessionLocaleResolver; 13 | 14 | import java.util.Locale; 15 | 16 | 17 | @Configuration 18 | public class WebMvcConfig implements WebMvcConfigurer { 19 | 20 | @Bean 21 | public LocaleResolver localeResolver(){ 22 | SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); 23 | sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH); 24 | 25 | return sessionLocaleResolver; 26 | } 27 | 28 | @Bean 29 | public LocaleChangeInterceptor localeChangeInterceptor() { 30 | LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); 31 | localeChangeInterceptor.setParamName("lang"); 32 | 33 | return localeChangeInterceptor; 34 | } 35 | 36 | @Bean 37 | public MessageSource messageSource(){ 38 | ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 39 | messageSource.setBasename("classpath:i18n/messages"); 40 | messageSource.setDefaultEncoding("UTF-8"); 41 | return messageSource; 42 | } 43 | 44 | @Override 45 | public void addInterceptors(InterceptorRegistry registry) { 46 | registry.addInterceptor(localeChangeInterceptor()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.config; 2 | 3 | import com.syqu.shop.service.impl.UserDetailsServiceImpl; 4 | import com.syqu.shop.repository.UserRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 16 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 17 | 18 | @Configuration 19 | @EnableWebSecurity 20 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 21 | private final UserRepository userRepository; 22 | 23 | @Autowired 24 | public WebSecurityConfig(UserRepository userRepository) { 25 | this.userRepository = userRepository; 26 | } 27 | 28 | @Bean 29 | public UserDetailsService userDetailsService() { 30 | return new UserDetailsServiceImpl(userRepository); 31 | } 32 | 33 | 34 | @Bean 35 | public BCryptPasswordEncoder passwordEncoder() { 36 | return new BCryptPasswordEncoder(); 37 | } 38 | 39 | @Bean 40 | @Override 41 | protected AuthenticationManager authenticationManager() throws Exception { 42 | return super.authenticationManager(); 43 | } 44 | 45 | @Override 46 | protected void configure(HttpSecurity http) throws Exception { 47 | http.csrf().disable().authorizeRequests() 48 | .antMatchers("/","/home","/index","/about","/help","/register","/cart/**").permitAll() 49 | .antMatchers("/user/**").hasRole("USER") 50 | .antMatchers("/admin/**","/product/new").hasRole("ADMIN") 51 | .and().formLogin().loginPage("/login").permitAll() 52 | .and().logout().invalidateHttpSession(true).clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll() 53 | .and().headers().frameOptions().sameOrigin(); 54 | } 55 | 56 | @Override 57 | public void configure(WebSecurity web) { 58 | web.ignoring().antMatchers("/webjars/**", "/js/**","/error/**" 59 | , "/css/**","/fonts/**","/libs/**","/img/**","/h2-console/**"); 60 | } 61 | 62 | @Autowired 63 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 64 | auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder()); 65 | } 66 | } -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/controller/CartController.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import com.syqu.shop.service.ShoppingCartService; 4 | import com.syqu.shop.domain.Product; 5 | import com.syqu.shop.service.ProductService; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.ui.Model; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | 14 | @Controller 15 | public class CartController { 16 | private static final Logger logger = LoggerFactory.getLogger(CartController.class); 17 | private final ShoppingCartService shoppingCartService; 18 | private final ProductService productService; 19 | 20 | @Autowired 21 | public CartController(ShoppingCartService shoppingCartService, ProductService productService) { 22 | this.shoppingCartService = shoppingCartService; 23 | this.productService = productService; 24 | } 25 | 26 | @GetMapping("/cart") 27 | public String cart(Model model){ 28 | model.addAttribute("products", shoppingCartService.productsInCart()); 29 | model.addAttribute("totalPrice", shoppingCartService.totalPrice()); 30 | 31 | return "cart"; 32 | } 33 | 34 | @GetMapping("/cart/add/{id}") 35 | public String addProductToCart(@PathVariable("id") long id){ 36 | Product product = productService.findById(id); 37 | if (product != null){ 38 | shoppingCartService.addProduct(product); 39 | logger.debug(String.format("Product with id: %s added to shopping cart.", id)); 40 | } 41 | return "redirect:/home"; 42 | } 43 | 44 | @GetMapping("/cart/remove/{id}") 45 | public String removeProductFromCart(@PathVariable("id") long id){ 46 | Product product = productService.findById(id); 47 | if (product != null){ 48 | shoppingCartService.removeProduct(product); 49 | logger.debug(String.format("Product with id: %s removed from shopping cart.", id)); 50 | } 51 | return "redirect:/cart"; 52 | } 53 | 54 | @GetMapping("/cart/clear") 55 | public String clearProductsInCart(){ 56 | shoppingCartService.clearProducts(); 57 | 58 | return "redirect:/cart"; 59 | } 60 | 61 | @GetMapping("/cart/checkout") 62 | public String cartCheckout(){ 63 | shoppingCartService.cartCheckout(); 64 | 65 | return "redirect:/cart"; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/controller/HomeController.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import com.syqu.shop.domain.Product; 4 | import com.syqu.shop.service.CategoryService; 5 | import com.syqu.shop.service.ProductService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.ui.Model; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestParam; 12 | 13 | import java.util.List; 14 | 15 | @Controller 16 | public class HomeController { 17 | private final ProductService productService; 18 | 19 | @Autowired 20 | private CategoryService categoryService; 21 | 22 | @Autowired 23 | public HomeController(ProductService productService) { 24 | this.productService = productService; 25 | } 26 | 27 | @GetMapping(value = {"/","/index","/home"}) 28 | public String home(Model model){ 29 | model.addAttribute("products", getAllProducts()); 30 | model.addAttribute("productsCount", productsCount()); 31 | model.addAttribute("categories", categoryService.findAll()); 32 | return "home"; 33 | } 34 | 35 | @RequestMapping("/searchByCategory") 36 | public String homePost(@RequestParam("categoryId") long categoryId, Model model){ 37 | model.addAttribute("books", productService.findAllByCategoryId(categoryId)); 38 | model.addAttribute("booksCount", productService.count()); 39 | model.addAttribute("categories", categoryService.findAll()); 40 | return "home"; 41 | } 42 | 43 | @GetMapping("/about") 44 | public String about(){ 45 | return "about"; 46 | } 47 | 48 | private List getAllProducts(){ 49 | return productService.findAllByOrderByIdAsc(); 50 | } 51 | 52 | private long productsCount(){ 53 | return productService.count(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.ui.Model; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | 7 | @Controller 8 | public class LoginController { 9 | 10 | @GetMapping("/login") 11 | public String login(Model model, String error){ 12 | if (error != null) 13 | model.addAttribute("error", "Your username and password is invalid."); 14 | 15 | return "login"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/controller/ProductController.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import com.syqu.shop.domain.Product; 4 | import com.syqu.shop.service.CategoryService; 5 | import com.syqu.shop.service.ProductService; 6 | import com.syqu.shop.validator.ProductValidator; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Controller; 11 | import org.springframework.ui.Model; 12 | import org.springframework.validation.BindingResult; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.ModelAttribute; 15 | import org.springframework.web.bind.annotation.PathVariable; 16 | import org.springframework.web.bind.annotation.PostMapping; 17 | 18 | @Controller 19 | public class ProductController { 20 | private static final Logger logger = LoggerFactory.getLogger(ProductController.class); 21 | private final ProductService productService; 22 | private final ProductValidator productValidator; 23 | private final CategoryService categoryService; 24 | 25 | @Autowired 26 | public ProductController(ProductService productService, ProductValidator productValidator, CategoryService categoryService) { 27 | this.productService = productService; 28 | this.productValidator = productValidator; 29 | this.categoryService = categoryService; 30 | } 31 | 32 | @GetMapping("/product/new") 33 | public String newProduct(Model model) { 34 | model.addAttribute("productForm", new Product()); 35 | model.addAttribute("method", "new"); 36 | model.addAttribute("categories", categoryService.findAll()); 37 | return "product"; 38 | } 39 | 40 | @PostMapping("/product/new") 41 | public String newProduct(@ModelAttribute("productForm") Product productForm, BindingResult bindingResult, Model model) { 42 | productValidator.validate(productForm, bindingResult); 43 | 44 | if (bindingResult.hasErrors()) { 45 | logger.error(String.valueOf(bindingResult.getFieldError())); 46 | model.addAttribute("method", "new"); 47 | return "product"; 48 | } 49 | productService.save(productForm); 50 | logger.debug(String.format("Product with id: %s successfully created.", productForm.getId())); 51 | 52 | return "redirect:/home"; 53 | } 54 | 55 | @GetMapping("/product/edit/{id}") 56 | public String editProduct(@PathVariable("id") long productId, Model model){ 57 | Product product = productService.findById(productId); 58 | if (product != null){ 59 | model.addAttribute("productForm", product); 60 | model.addAttribute("method", "edit"); 61 | return "product"; 62 | }else { 63 | return "error/404"; 64 | } 65 | } 66 | 67 | @PostMapping("/product/edit/{id}") 68 | public String editProduct(@PathVariable("id") long productId, @ModelAttribute("productForm") Product productForm, BindingResult bindingResult, Model model){ 69 | productValidator.validate(productForm, bindingResult); 70 | 71 | if (bindingResult.hasErrors()) { 72 | logger.error(String.valueOf(bindingResult.getFieldError())); 73 | model.addAttribute("method", "edit"); 74 | return "product"; 75 | } 76 | productService.edit(productId, productForm); 77 | logger.debug(String.format("Product with id: %s has been successfully edited.", productId)); 78 | 79 | return "redirect:/home"; 80 | } 81 | 82 | @PostMapping("/product/delete/{id}") 83 | public String deleteProduct(@PathVariable("id") long productId){ 84 | Product product = productService.findById(productId); 85 | if (product != null){ 86 | productService.delete(productId); 87 | logger.debug(String.format("Product with id: %s successfully deleted.", product.getId())); 88 | return "redirect:/home"; 89 | }else { 90 | return "error/404"; 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/controller/RegisterController.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import com.syqu.shop.domain.User; 4 | import com.syqu.shop.service.UserService; 5 | import com.syqu.shop.validator.UserValidator; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.ui.Model; 11 | import org.springframework.validation.BindingResult; 12 | import org.springframework.web.bind.annotation.GetMapping; 13 | import org.springframework.web.bind.annotation.ModelAttribute; 14 | import org.springframework.web.bind.annotation.PostMapping; 15 | 16 | @Controller 17 | public class RegisterController { 18 | private static final Logger logger = LoggerFactory.getLogger(RegisterController.class); 19 | private final UserService userService; 20 | private final UserValidator userValidator; 21 | 22 | @Autowired 23 | public RegisterController(UserService userService, UserValidator userValidator) { 24 | this.userService = userService; 25 | this.userValidator = userValidator; 26 | } 27 | 28 | @GetMapping("/register") 29 | public String registration(Model model) { 30 | model.addAttribute("userForm", new User()); 31 | 32 | return "register"; 33 | } 34 | 35 | @PostMapping("/register") 36 | public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult) { 37 | userValidator.validate(userForm, bindingResult); 38 | 39 | if (bindingResult.hasErrors()) { 40 | logger.error(String.valueOf(bindingResult.getFieldError())); 41 | return "register"; 42 | } 43 | 44 | userService.save(userForm); 45 | userService.login(userForm.getUsername(), userForm.getPasswordConfirm()); 46 | 47 | return "redirect:/home"; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import com.syqu.shop.domain.User; 4 | import com.syqu.shop.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.ui.Model; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | 10 | import java.security.Principal; 11 | 12 | @Controller 13 | public class UserController { 14 | private final UserService userService; 15 | 16 | @Autowired 17 | public UserController(UserService userService) { 18 | this.userService = userService; 19 | } 20 | 21 | @GetMapping("/user") 22 | public String userPanel(Principal principal, Model model){ 23 | User user = userService.findByUsername(principal.getName()); 24 | 25 | if (user != null) { 26 | model.addAttribute("user", user); 27 | }else { 28 | return "error/404"; 29 | } 30 | 31 | return "user"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/domain/Category.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.domain; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import javax.validation.constraints.NotEmpty; 7 | import javax.validation.constraints.NotNull; 8 | import java.util.HashSet; 9 | import java.util.Objects; 10 | import java.util.Set; 11 | 12 | 13 | @Entity 14 | @Data 15 | @Table(name = "category") 16 | public class Category { 17 | @Column(name = "id") 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.AUTO) 20 | private long id; 21 | 22 | @Column(name = "cat_name") 23 | @NotNull 24 | @NotEmpty 25 | private String categoryName; 26 | 27 | @OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL) 28 | private Set books = new HashSet<>(); 29 | 30 | @Override 31 | public boolean equals(Object o) { 32 | if (this == o) return true; 33 | if (o == null || getClass() != o.getClass()) return false; 34 | Category category = (Category) o; 35 | 36 | return id == category.getId(); 37 | } 38 | 39 | @Override 40 | public int hashCode() { 41 | return Objects.hash(id); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/domain/Product.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.domain; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import javax.validation.constraints.NotEmpty; 7 | import javax.validation.constraints.NotNull; 8 | import java.math.BigDecimal; 9 | import java.util.Objects; 10 | 11 | @Data 12 | @Entity 13 | @Table(name = "product") 14 | public class Product { 15 | 16 | @Column(name = "id") 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.AUTO) 19 | private long id; 20 | 21 | @Column(name = "name") 22 | @NotNull 23 | @NotEmpty 24 | private String name; 25 | 26 | @ManyToOne(fetch = FetchType.LAZY) 27 | @JoinColumn(name = "category_id", nullable = true) 28 | private Category category; 29 | 30 | @Column(name = "description",length = 500) 31 | @NotNull 32 | @NotEmpty 33 | private String description; 34 | 35 | @Column(name = "image") 36 | private String imageUrl; 37 | 38 | @Column(name = "price") 39 | @NotNull 40 | private BigDecimal price; 41 | 42 | @Override 43 | public boolean equals(Object o) { 44 | if (this == o) return true; 45 | if (o == null || getClass() != o.getClass()) return false; 46 | Product product = (Product) o; 47 | 48 | return id == product.getId(); 49 | } 50 | 51 | @Override 52 | public int hashCode() { 53 | return Objects.hash(id); 54 | } 55 | 56 | } 57 | 58 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.domain; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import javax.validation.constraints.Email; 7 | import javax.validation.constraints.NotEmpty; 8 | import javax.validation.constraints.NotNull; 9 | import java.math.BigDecimal; 10 | 11 | @Data 12 | @Entity 13 | @Table(name = "user") 14 | public class User { 15 | 16 | @Column(name = "id") 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.AUTO) 19 | private long id; 20 | 21 | @Column(name = "username", unique = true) 22 | @NotEmpty 23 | @NotNull 24 | private String username; 25 | 26 | @Column(name = "email", unique = true) 27 | @Email 28 | @NotEmpty 29 | @NotNull 30 | private String email; 31 | 32 | @NotEmpty 33 | @NotNull 34 | private String password; 35 | 36 | @NotEmpty 37 | @NotNull 38 | private String passwordConfirm; 39 | 40 | @Column(name = "first_name") 41 | private String firstName; 42 | 43 | @Column(name = "last_name") 44 | private String lastName; 45 | 46 | @Column(name = "age") 47 | private int age; 48 | 49 | @Column(name = "city") 50 | private String city; 51 | 52 | @Column(name = "gender") 53 | @NotEmpty 54 | @NotNull 55 | private String gender; 56 | 57 | @Column(name = "balance") 58 | private BigDecimal balance; 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/repository/CategoryRepository.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.repository; 2 | 3 | import com.syqu.shop.domain.Category; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface CategoryRepository extends JpaRepository { 7 | Category findByCategoryName(String name); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/repository/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.repository; 2 | 3 | import com.syqu.shop.domain.Product; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.List; 8 | 9 | @Repository 10 | public interface ProductRepository extends JpaRepository { 11 | Product findById(long id); 12 | Product findByName(String name); 13 | List findAllByOrderByIdAsc(); 14 | List findAllByCategoryId(long categoryId); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.repository; 2 | 3 | import com.syqu.shop.domain.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface UserRepository extends JpaRepository { 9 | User findByUsername(String username); 10 | User findByEmail(String email); 11 | User findById(long id); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/CategoryService.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service; 2 | 3 | import com.syqu.shop.domain.Category; 4 | 5 | import java.util.List; 6 | 7 | 8 | public interface CategoryService { 9 | 10 | void save(Category category); 11 | List findAll(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/ProductService.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service; 2 | 3 | import com.syqu.shop.domain.Product; 4 | 5 | import java.util.List; 6 | 7 | public interface ProductService { 8 | void save(Product product); 9 | void edit(long id, Product newProduct); 10 | void delete(long id); 11 | Product findById(long id); 12 | List findAllByOrderByIdAsc(); 13 | List findAllByCategoryId(long categoryId); 14 | long count(); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/ShoppingCartService.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service; 2 | 3 | import com.syqu.shop.domain.Product; 4 | import org.springframework.stereotype.Service; 5 | 6 | import java.math.BigDecimal; 7 | import java.util.Map; 8 | 9 | @Service 10 | public interface ShoppingCartService { 11 | void addProduct(Product product); 12 | void removeProduct(Product product); 13 | void clearProducts(); 14 | Map productsInCart(); 15 | BigDecimal totalPrice(); 16 | void cartCheckout(); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service; 2 | 3 | import com.syqu.shop.domain.User; 4 | 5 | public interface UserService { 6 | void save(User user); 7 | void login(String username, String password); 8 | User findByUsername(String username); 9 | User findByEmail(String email); 10 | User findById(long id); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/impl/CategoryServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service.impl; 2 | 3 | import com.syqu.shop.domain.Category; 4 | import com.syqu.shop.repository.CategoryRepository; 5 | import com.syqu.shop.service.CategoryService; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | 10 | @Service 11 | public class CategoryServiceImpl implements CategoryService { 12 | 13 | private final CategoryRepository categoryRepository; 14 | 15 | public CategoryServiceImpl(CategoryRepository categoryRepository) { 16 | this.categoryRepository = categoryRepository; 17 | } 18 | 19 | 20 | @Override 21 | public void save(Category category) { 22 | categoryRepository.save(category); 23 | } 24 | 25 | @Override 26 | public List findAll() { 27 | return categoryRepository.findAll(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/impl/ProductServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service.impl; 2 | 3 | import com.syqu.shop.domain.Product; 4 | import com.syqu.shop.repository.ProductRepository; 5 | import com.syqu.shop.service.ProductService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.List; 10 | 11 | @Service 12 | public class ProductServiceImpl implements ProductService { 13 | private final ProductRepository productRepository; 14 | 15 | @Autowired 16 | public ProductServiceImpl(ProductRepository productRepository){ 17 | this.productRepository = productRepository; 18 | } 19 | 20 | @Override 21 | public void save(Product product) { 22 | productRepository.save(product); 23 | } 24 | 25 | @Override 26 | public void edit(long id, Product newProduct) { 27 | Product found = productRepository.getOne(id); 28 | found.setName(newProduct.getName()); 29 | found.setImageUrl(newProduct.getImageUrl()); 30 | found.setDescription(newProduct.getDescription()); 31 | found.setPrice(newProduct.getPrice()); 32 | save(newProduct); 33 | } 34 | 35 | @Override 36 | public void delete(long id) { 37 | productRepository.delete(findById(id)); 38 | } 39 | 40 | @Override 41 | public Product findById(long id) { 42 | return productRepository.findById(id); 43 | } 44 | 45 | @Override 46 | public List findAllByOrderByIdAsc() { 47 | return productRepository.findAllByOrderByIdAsc(); 48 | } 49 | 50 | @Override 51 | public List findAllByCategoryId(long categoryId) { 52 | return productRepository.findAllByCategoryId(categoryId); 53 | } 54 | 55 | @Override 56 | public long count() { 57 | return productRepository.count(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/impl/ShoppingCartServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service.impl; 2 | 3 | import com.syqu.shop.domain.Product; 4 | import com.syqu.shop.service.ShoppingCartService; 5 | import org.springframework.context.annotation.Scope; 6 | import org.springframework.context.annotation.ScopedProxyMode; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | import org.springframework.web.context.WebApplicationContext; 10 | 11 | import java.math.BigDecimal; 12 | import java.util.Collections; 13 | import java.util.LinkedHashMap; 14 | import java.util.Map; 15 | 16 | /* 17 | Thanks to Dusan! 18 | www.github.com/reljicd/spring-boot-shopping-cart 19 | */ 20 | 21 | @Service 22 | @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) 23 | @Transactional 24 | public class ShoppingCartServiceImpl implements ShoppingCartService { 25 | private Map cart = new LinkedHashMap<>(); 26 | 27 | @Override 28 | public void addProduct(Product product) { 29 | if (cart.containsKey(product)){ 30 | cart.replace(product, cart.get(product) + 1); 31 | }else{ 32 | cart.put(product, 1); 33 | } 34 | } 35 | 36 | @Override 37 | public void removeProduct(Product product) { 38 | if (cart.containsKey(product)) { 39 | if (cart.get(product) > 1) 40 | cart.replace(product, cart.get(product) - 1); 41 | else if (cart.get(product) == 1) { 42 | cart.remove(product); 43 | } 44 | } 45 | } 46 | 47 | @Override 48 | public void clearProducts() { 49 | cart.clear(); 50 | } 51 | 52 | @Override 53 | public Map productsInCart() { 54 | return Collections.unmodifiableMap(cart); 55 | } 56 | 57 | @Override 58 | public BigDecimal totalPrice() { 59 | return cart.entrySet().stream() 60 | .map(k -> k.getKey().getPrice().multiply(BigDecimal.valueOf(k.getValue()))).sorted() 61 | .reduce(BigDecimal::add) 62 | .orElse(BigDecimal.ZERO); 63 | } 64 | 65 | @Override 66 | public void cartCheckout() { 67 | cart.clear(); 68 | // Normally there would be payment etc. 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/impl/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service.impl; 2 | 3 | import com.syqu.shop.domain.User; 4 | import com.syqu.shop.repository.UserRepository; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.security.core.GrantedAuthority; 9 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.stereotype.Service; 14 | import org.springframework.transaction.annotation.Transactional; 15 | 16 | import java.util.HashSet; 17 | import java.util.Objects; 18 | import java.util.Set; 19 | 20 | @Service 21 | public class UserDetailsServiceImpl implements UserDetailsService { 22 | private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class); 23 | private final UserRepository userRepository; 24 | 25 | @Autowired 26 | public UserDetailsServiceImpl(UserRepository userRepository) { 27 | this.userRepository = userRepository; 28 | } 29 | 30 | @Override 31 | @Transactional(readOnly = true) 32 | public UserDetails loadUserByUsername(String username){ 33 | User user = userRepository.findByUsername(username); 34 | 35 | if (user != null) { 36 | Set authorities = new HashSet<>(); 37 | if (Objects.equals(username, "admin")) { 38 | authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); 39 | }else { 40 | authorities.add(new SimpleGrantedAuthority("ROLE_USER")); 41 | } 42 | logger.debug(String.format("User with name: %s and password: %s created.", user.getUsername(), user.getPassword())); 43 | return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities); 44 | }else{ 45 | throw new UsernameNotFoundException("User " + username + " not found!"); 46 | } 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service.impl; 2 | 3 | import com.syqu.shop.service.UserService; 4 | import com.syqu.shop.domain.User; 5 | import com.syqu.shop.repository.UserRepository; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 11 | import org.springframework.security.core.context.SecurityContextHolder; 12 | import org.springframework.security.core.userdetails.UserDetails; 13 | import org.springframework.security.core.userdetails.UserDetailsService; 14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 15 | import org.springframework.stereotype.Service; 16 | 17 | @Service 18 | public class UserServiceImpl implements UserService { 19 | private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); 20 | private final UserRepository userRepository; 21 | private final UserDetailsService userDetailsService; 22 | private final BCryptPasswordEncoder bCryptPasswordEncoder; 23 | private final AuthenticationManager authenticationManager; 24 | 25 | @Autowired 26 | public UserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder, UserDetailsService userDetailsService, AuthenticationManager authenticationManager) { 27 | this.userRepository = userRepository; 28 | this.bCryptPasswordEncoder = bCryptPasswordEncoder; 29 | this.userDetailsService = userDetailsService; 30 | this.authenticationManager = authenticationManager; 31 | } 32 | 33 | @Override 34 | public void save(User user) { 35 | user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); 36 | userRepository.save(user); 37 | } 38 | 39 | @Override 40 | public void login(String username, String password) { 41 | UserDetails userDetails = userDetailsService.loadUserByUsername(username); 42 | UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities()); 43 | authenticationManager.authenticate(token); 44 | 45 | if (token.isAuthenticated()) { 46 | SecurityContextHolder.getContext().setAuthentication(token); 47 | logger.debug(String.format("User %s logged in successfully!", username)); 48 | }else{ 49 | logger.error(String.format("Error with %s authentication!", username)); 50 | } 51 | } 52 | 53 | @Override 54 | public User findByUsername(String username) { 55 | return userRepository.findByUsername(username); 56 | } 57 | 58 | @Override 59 | public User findByEmail(String email) { 60 | return userRepository.findByEmail(email); 61 | } 62 | 63 | @Override 64 | public User findById(long id) { 65 | return userRepository.findById(id); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/validator/ProductValidator.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.validator; 2 | 3 | import com.syqu.shop.domain.Product; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.validation.Errors; 6 | import org.springframework.validation.ValidationUtils; 7 | import org.springframework.validation.Validator; 8 | 9 | @Component 10 | public class ProductValidator implements Validator { 11 | 12 | @Override 13 | public boolean supports(Class aClass) { 14 | return Product.class.equals(aClass); 15 | } 16 | 17 | @Override 18 | public void validate(Object o, Errors errors) { 19 | Product product = (Product) o; 20 | 21 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name","error.not_empty"); 22 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "error.not_empty"); 23 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "error.not_empty"); 24 | 25 | // Name must have from 2 characters to 32 26 | if (product.getName().length() <= 1) { 27 | errors.rejectValue("name", "product.error.name.less_2"); 28 | } 29 | if (product.getName().length() > 32) { 30 | errors.rejectValue("name", "product.error.name.over_32"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/syqu/shop/validator/UserValidator.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.validator; 2 | 3 | import com.syqu.shop.domain.User; 4 | import com.syqu.shop.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.validation.Errors; 8 | import org.springframework.validation.ValidationUtils; 9 | import org.springframework.validation.Validator; 10 | 11 | @Component 12 | public class UserValidator implements Validator { 13 | private final UserService userService; 14 | 15 | @Autowired 16 | public UserValidator(UserService userService) { 17 | this.userService = userService; 18 | } 19 | 20 | @Override 21 | public boolean supports(Class aClass) { 22 | return User.class.equals(aClass); 23 | } 24 | 25 | @Override 26 | public void validate(Object o, Errors errors) { 27 | User user = (User) o; 28 | 29 | //Username and password can't me empty or contain whitespace 30 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.not_empty"); 31 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.not_empty"); 32 | 33 | // Username must have from 4 characters to 32 34 | if (user.getUsername().length() < 4) { 35 | errors.rejectValue("username", "register.error.username.less_4"); 36 | } 37 | if(user.getUsername().length() > 32){ 38 | errors.rejectValue("username","register.error.username.over_32"); 39 | } 40 | //Username can't be duplicated 41 | if (userService.findByUsername(user.getUsername()) != null) { 42 | errors.rejectValue("username", "register.error.duplicated.username"); 43 | } 44 | //Email can't be duplicated 45 | if (userService.findByEmail(user.getEmail()) != null){ 46 | errors.rejectValue("email", "register.error.duplicated.email"); 47 | } 48 | //Password must have at least 8 characters and max 32 49 | if (user.getPassword().length() < 8) { 50 | errors.rejectValue("password", "register.error.password.less_8"); 51 | } 52 | if (user.getPassword().length() > 32){ 53 | errors.rejectValue("password", "register.error.password.over_32"); 54 | } 55 | //Password must be the same as the confirmation password 56 | if (!user.getPasswordConfirm().equals(user.getPassword())) { 57 | errors.rejectValue("passwordConfirm", "register.error.diff_password"); 58 | } 59 | //Age needs to be higher than 13 60 | if (user.getAge() <= 13){ 61 | errors.rejectValue("age", "register.error.age_size"); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #Port 2 | server.port=8080 3 | 4 | #Main 5 | spring.application.name=E-shop N3XT 6 | 7 | #Thymeleaf 8 | spring.thymeleaf.cache=false 9 | 10 | #JPA 11 | spring.jpa.hibernate.ddl-auto=create 12 | spring.jpa.show-sql=true 13 | 14 | # H2 DB 15 | spring.h2.console.enabled=true 16 | spring.datasource.hikari.driver-class-name=org.h2.Driver 17 | spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb 18 | spring.datasource.hikari.username=sa 19 | spring.datasource.hikari.password= 20 | 21 | #Logging 22 | logging.level.org.springframework.jdbc=debug 23 | 24 | #Template Engine 25 | spring.mvc.view.prefix=classpath:/templates/ 26 | spring.mvc.view.suffix=.html 27 | -------------------------------------------------------------------------------- /src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | _____ _ _ _ _____ __ __ _____ 2 | | ___| | | | \ | ||____ |\ \ / /|_ _| 3 | | |__ ______ ___ | |__ ___ _ __ | \| | / / \ V / | | 4 | | __| |______|/ __|| '_ \ / _ \ | '_ \ | . ` | \ \ / \ | | 5 | | |___ \__ \| | | || (_) || |_) | | |\ |.___/ // /^\ \ | | 6 | \____/ |___/|_| |_| \___/ | .__/ \_| \_/\____/ \/ \/ \_/ 7 | | | 8 | |_| 9 | 10 | :: Spring Boot Version :: ${spring-boot.version} 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/i18n/messages.properties: -------------------------------------------------------------------------------- 1 | footer.copyright=\u00A92018 by Aleksander Lejawa - aleklejawa@gmail.com 2 | footer.language.en=English 3 | footer.language.pl=Polish 4 | footer.language.den=German 5 | user.log_in=Log In 6 | user.log_out=Log Out 7 | user.username=Username 8 | user.email=E-mail 9 | user.password=Password 10 | user.confirm_password=Confirm password 11 | user.firstname=First Name 12 | user.lastname=Last Name 13 | user.city=City 14 | user.gender=Gender 15 | user.gender.hidden=Hidden 16 | user.gender.male=Male 17 | user.gender.female=Female 18 | user.age=Age 19 | admin.create.product=Add new product 20 | product.name=Name 21 | product.category=Category 22 | product.desc=Description 23 | product.image_url=Image Url 24 | product.price=Price 25 | product.confirm=Confirm new product 26 | product.add=Add to cart 27 | register.title=Registration 28 | register.button=Register 29 | register.required=Fields with * are required! 30 | error.not_empty=This field can't be empty. 31 | register.error.diff_password=Passwords needs to be the same. 32 | register.error.duplicated.email=This E-mail is already in use. 33 | register.error.duplicated.username=This username is already in use. 34 | register.error.age_size=You need at least 13 years to register. 35 | register.error.password.less_8=Password must have at least 8 characters. 36 | register.error.password.over_32=Password can't have more than 32 characters. 37 | register.error.username.less_4=Username must have at least 4 characters. 38 | register.error.username.over_32=Username can't have more than 32 characters. 39 | header.app.title=E-shop N3XT 40 | header.logged=Logged as: 41 | header.search=Search 42 | login.sign_in=Please Sign In 43 | login.no_account=You don't have an account? 44 | login.alert.logged_out=You have been logged out. 45 | about.name=About me 46 | about.title=About me 47 | about.text=Hello my name is Aleksander and i am from Poland. That is all, thanks for visiting this page. :) 48 | home.title=Hello World! 49 | home.back=Back to home 50 | error.title=Error: 51 | error.no_access=Sorry, you can't access this page. 52 | error.no_page=Looks like this page doesn't exist. 53 | error.internal=Internal server error. 54 | error.unhandled=Unhandled error. 55 | product.error.name.less_2=Name must have at least 2 characters. 56 | product.error.name.over_32=Title can't have more than 32 characters. 57 | product.cancel=Cancel 58 | product.count=Total products: 59 | cart.remove=Remove 60 | cart.clear=Clear 61 | cart.title=Cart 62 | cart.total=Total price: 63 | cart.checkout=Checkout 64 | cart.empty=Looks like your cart is empty. 65 | user.title=User -------------------------------------------------------------------------------- /src/main/resources/i18n/messages_pl.properties: -------------------------------------------------------------------------------- 1 | footer.copyright=\u00A92018 by Aleksander Lejawa - aleklejawa@gmail.com 2 | footer.language.en=Angielski 3 | footer.language.pl=Polski 4 | footer.language.den=Niemiecki 5 | user.log_in=Zaloguj si\u0119 6 | user.log_out=Wyloguj si\u0119 7 | user.username=Nazwa u\u017Cytkownika 8 | user.email=Adres E-Mail 9 | user.password=Has\u0142o 10 | user.confirm_password=Powt\u00F3rz has\u0142o 11 | user.firstname=Imi\u0119 12 | user.lastname=Nazwisko 13 | user.city=Miasto 14 | user.gender=P\u0142e\u0107 15 | user.gender.hidden=Ukryta 16 | user.gender.male=M\u0119\u017Cczyzna 17 | user.gender.female=Kobieta 18 | user.age=Wiek 19 | admin.create.product=Utw\u00F3rz nowy produkt 20 | product.name=Nazwa 21 | product.desc=Opis 22 | product.image_url=Link do zdj\u0119cia 23 | product.price=Cena 24 | register.title=Rejestracja 25 | register.button=Zarejestruj si\u0119 26 | register.required=Pola z * s\u0105 wymagane! 27 | error.not_empty=To pole nie mo\u017Ce by\u0107 puste. 28 | register.error.diff_password=Has\u0142a musz\u0105 by\u0107 takie same. 29 | register.error.duplicated.email=Ten adres E-mail jest ju\u017C zaj\u0119ty. 30 | register.error.duplicated.username=Ta nazwa u\u017Cytkownika jest ju\u017C zaj\u0119ta. 31 | register.error.age_size=Musisz mie\u0107 przynajmniej 13 lat by dokona\u0107 rejestracji. 32 | register.error.password.less_8=Has\u0142o musi mie\u0107 przynajmniej 8 znak\u00F3w. 33 | register.error.password.over_32=Has\u0142o nie mo\u017Ce mie\u0107 wi\u0119cej ni\u017C 32 znaki. 34 | register.error.username.less_4=Nazwa u\u017Cytkownika musi mie\u0107 przynajmniej 4 znaki. 35 | register.error.username.over_32=Nazwa u\u017Cytkownika nie mo\u017Ce mie wi\u0119cej ni\u017C 32 znaki. 36 | header.app.title=E-shop N3XT 37 | header.logged=Zalogowany jako: 38 | header.search=Szukaj 39 | login.sign_in=Prosze si\u0119 zalogowa\u0107 40 | login.no_account=Nie masz jeszcze konta? 41 | login.alert.logged_out=Zosta\u0142e\u015B pomy\u015Blnie wylogowany. 42 | about.name=O mnie 43 | about.title=O mnie 44 | about.text=Cze\u015B\u0107, nazywam si\u00EA Aleksander i pochodz\u0119 z Polski. To wszystko, dzi\u0119kuje za odwiedzenie mojej strony. :) 45 | home.title=Witaj \u015Bwiecie! 46 | home.back=Powr\u00F3t do strony g\u0142\u00F3wnej 47 | error.title=B\u0142\u0105d: 48 | error.no_access=Nie masz wymaganych uprawnie\u0144. 49 | error.no_page=Wygl\u0105da na to, \u017Ce podana strona nie istnieje. 50 | error.internal=B\u0142\u0105d serwera. 51 | error.unhandled=Nieobs\u0142ugiwany b\u0142\u0105d. 52 | product.add=Dodaj do koszyka 53 | product.error.name.over_32=Tytu\u0142 nie mo\u017Ce mie\u0107 wi\u0119cej ni\u017C 32 znaki. 54 | product.error.name.less_2=Nazwa musi mie\u0107 przynajmniej 8 znak\u00F3w. 55 | product.cancel=Anuluj 56 | product.count=\u0141\u0105czna liczba produkt\u00F3w: 57 | cart.remove=Usu\u0144 58 | cart.clear=Wyczy\u015B\u0107 59 | cart.title=Koszyk 60 | cart.total=\u0141\u0105czna cena: 61 | cart.checkout=Finalizuj 62 | cart.empty=Wygl\u0105da na to \u017Ce tw\u00F3j koszyk jest pusty. 63 | user.title=U\u017Cytkownik -------------------------------------------------------------------------------- /src/main/resources/static/css/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | height: 100%; 3 | } 4 | 5 | body { 6 | background: rgb(209, 209, 216); 7 | position: relative; 8 | margin: 0; 9 | padding-bottom: 6rem; 10 | min-height: 100%; 11 | } 12 | 13 | span { 14 | padding-left: 5px; 15 | padding-right: 5px; 16 | } 17 | 18 | footer { 19 | position: absolute; 20 | bottom: 0; 21 | line-height: 50px; 22 | } 23 | 24 | .container { 25 | padding-top: 15px; 26 | padding-bottom: 8px; 27 | } 28 | 29 | .btn { 30 | padding-left: 10px; 31 | } 32 | 33 | .alert { 34 | padding-top: 5px; 35 | } 36 | 37 | #header-username{ 38 | color: ghostwhite; 39 | } 40 | 41 | nav { 42 | height: 60px; 43 | } 44 | 45 | .navbar-brand { 46 | font-size: 30px; 47 | padding-left: 10px; 48 | padding-right: 15px; 49 | transition: all 300ms; 50 | } 51 | 52 | .navbar-brand:hover, .info-slide:active { 53 | transform: scale(1.5); 54 | } 55 | 56 | .card-deck { 57 | padding-left: 20px; 58 | } 59 | 60 | .card { 61 | max-width: 17rem; 62 | } 63 | 64 | #cart { 65 | width: 44px; 66 | height: 44px; 67 | } -------------------------------------------------------------------------------- /src/main/resources/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/favicon.ico -------------------------------------------------------------------------------- /src/main/resources/static/images/brand.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/images/brand.png -------------------------------------------------------------------------------- /src/main/resources/static/images/brand.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | N3XT -------------------------------------------------------------------------------- /src/main/resources/static/images/cart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/images/cart.png -------------------------------------------------------------------------------- /src/main/resources/static/images/example1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/images/example1.PNG -------------------------------------------------------------------------------- /src/main/resources/static/js/lang.js: -------------------------------------------------------------------------------- 1 | function changeLanguage(lang) { 2 | let currentUrl = window.location.toString(); 3 | let cleanUrl = currentUrl.split("?")[0]; 4 | 5 | window.history.replace({}, window.title, cleanUrl + "?lang=" + lang); 6 | } 7 | 8 | $("#select-lang").change(function(){ 9 | changeLanguage($(this).val()); 10 | }); -------------------------------------------------------------------------------- /src/main/resources/templates/about.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 | 13 |
14 |

15 |

16 |
17 | 18 |
19 | 20 |
21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/resources/templates/cart.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |
13 |

14 |
15 |

16 |

17 |

18 | 19 | 20 | 21 |
22 |
23 |
24 | 25 |
26 |

27 |
28 | 29 |
30 | 31 | 32 | 33 | 34 |
35 |
36 |

"> 37 | 38 | 39 | 40 |
41 |
42 | 43 |
44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/main/resources/templates/error/403.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |
13 |

14 |

15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/resources/templates/error/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |
13 |

14 |

15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/resources/templates/error/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |
13 |

14 |

15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/resources/templates/error/error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |
13 |

14 |

15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/resources/templates/fragments/footer.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 |
10 |
11 | 12 | 13 | 14 | 15 | 22 |
23 |
24 | 25 | 26 | 27 |
28 | 29 | 30 | -------------------------------------------------------------------------------- /src/main/resources/templates/fragments/header.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 45 |
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/main/resources/templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |
13 | 19 | 20 | 23 |
24 |
25 |
26 | 29 | 32 |
33 | Card image cap 34 |
35 |

36 |

37 |
38 | 42 |
43 |
44 |
45 | 46 |
47 |
48 |
49 | 50 |
51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 |
10 |
11 |
12 | 40 |
41 |
42 |
43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /src/main/resources/templates/product.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |
13 |
14 |
15 |
16 |

17 |
18 | 19 | 20 |
21 |
22 |
23 | 24 | 29 |
30 |
31 | 32 | 33 |
34 |
35 |
36 | 37 | 38 |
39 |
40 |
41 | 42 | 43 |
44 |
45 | 46 | 47 |
48 |
49 |
50 |
51 |
52 | 53 |
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/main/resources/templates/register.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 |
10 |
11 |
12 | 68 |
69 |
70 |
71 |
72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/resources/templates/user.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 |
12 |

13 |
14 | 15 |

16 |

17 |

18 |

19 |

20 |
21 | 22 |
23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/controller/CartControllerMvcTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import com.syqu.shop.service.ShoppingCartService; 4 | import com.syqu.shop.service.ProductService; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.boot.test.mock.mockito.MockBean; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | import org.springframework.test.web.servlet.MockMvc; 12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 13 | import org.springframework.web.servlet.view.InternalResourceViewResolver; 14 | 15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 16 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 19 | 20 | @SpringBootTest 21 | @RunWith(SpringRunner.class) 22 | public class CartControllerMvcTests { 23 | private MockMvc mockMvc; 24 | 25 | @MockBean 26 | ShoppingCartService shoppingCartService; 27 | 28 | @MockBean 29 | ProductService productService; 30 | 31 | @Before 32 | public void setUp() { 33 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 34 | viewResolver.setPrefix("/WEB-INF/jsp/view/"); 35 | viewResolver.setSuffix(".jsp"); 36 | 37 | mockMvc = MockMvcBuilders.standaloneSetup(new CartController(shoppingCartService, productService)) 38 | .setViewResolvers(viewResolver) 39 | .build(); 40 | } 41 | 42 | @Test 43 | public void cartControllerStatus() throws Exception{ 44 | this.mockMvc.perform(get("/cart")).andExpect(status().isOk()) 45 | .andExpect(view().name("cart")).andDo(print()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/controller/ControllersTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | @SpringBootTest 12 | @RunWith(SpringRunner.class) 13 | public class ControllersTests { 14 | 15 | @Autowired 16 | HomeController homeController; 17 | @Autowired 18 | LoginController loginController; 19 | @Autowired 20 | RegisterController registerController; 21 | @Autowired 22 | UserController userController; 23 | @Autowired 24 | ProductController productController; 25 | @Autowired 26 | CartController cartController; 27 | 28 | @Test 29 | public void checkIfHomeControllerNotNull() { 30 | assertThat(homeController).isNotNull(); 31 | } 32 | 33 | @Test 34 | public void checkIfUserControllerNotNull() { 35 | assertThat(userController).isNotNull(); 36 | } 37 | 38 | @Test 39 | public void checkIfLoginControllerNotNull() { 40 | assertThat(loginController).isNotNull(); 41 | } 42 | 43 | @Test 44 | public void checkIfRegisterControllerNotNull() { 45 | assertThat(registerController).isNotNull(); 46 | } 47 | 48 | @Test 49 | public void checkIfProductControllerNotNull() { 50 | assertThat(productController).isNotNull(); 51 | } 52 | 53 | @Test 54 | public void checkIfCartControllerNotNull() { 55 | assertThat(cartController).isNotNull(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/controller/HomeControllerMvcTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | 4 | import com.syqu.shop.service.ProductService; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.boot.test.mock.mockito.MockBean; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | import org.springframework.test.web.servlet.MockMvc; 12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 13 | import org.springframework.web.servlet.view.InternalResourceViewResolver; 14 | 15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 16 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 19 | 20 | @SpringBootTest 21 | @RunWith(SpringRunner.class) 22 | public class HomeControllerMvcTests { 23 | private MockMvc mockMvc; 24 | 25 | @MockBean 26 | private ProductService productService; 27 | 28 | @Before 29 | public void setUp() { 30 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 31 | viewResolver.setPrefix("/WEB-INF/jsp/view/"); 32 | viewResolver.setSuffix(".jsp"); 33 | 34 | mockMvc = MockMvcBuilders.standaloneSetup(new HomeController(productService)) 35 | .setViewResolvers(viewResolver) 36 | .build(); 37 | } 38 | 39 | @Test 40 | public void homeControllerStatus() throws Exception{ 41 | this.mockMvc.perform(get("/")).andExpect(status().isOk()) 42 | .andExpect(view().name("home")).andDo(print()); 43 | } 44 | 45 | @Test 46 | public void homeControllerStatus2() throws Exception{ 47 | this.mockMvc.perform(get("/index")).andExpect(status().isOk()) 48 | .andExpect(view().name("home")).andDo(print()); 49 | } 50 | @Test 51 | 52 | public void homeControllerStatus3() throws Exception{ 53 | this.mockMvc.perform(get("/home")).andExpect(status().isOk()) 54 | .andExpect(view().name("home")).andDo(print()); 55 | } 56 | @Test 57 | 58 | public void homeControllerStatus4() throws Exception{ 59 | this.mockMvc.perform(get("/about")).andExpect(status().isOk()) 60 | .andExpect(view().name("about")).andDo(print()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/controller/LoginControllerMvcTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.controller; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | import org.springframework.test.web.servlet.MockMvc; 9 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 10 | import org.springframework.web.servlet.view.InternalResourceViewResolver; 11 | 12 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 13 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 14 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 15 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 16 | 17 | @SpringBootTest 18 | @RunWith(SpringRunner.class) 19 | public class LoginControllerMvcTests { 20 | private MockMvc mockMvc; 21 | 22 | @Before 23 | public void setUp() { 24 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 25 | viewResolver.setPrefix("/WEB-INF/jsp/view/"); 26 | viewResolver.setSuffix(".jsp"); 27 | 28 | mockMvc = MockMvcBuilders.standaloneSetup(new LoginController()) 29 | .setViewResolvers(viewResolver) 30 | .build(); 31 | } 32 | 33 | @Test 34 | public void loginControllerStatus() throws Exception{ 35 | this.mockMvc.perform(get("/login")).andExpect(status().isOk()) 36 | .andExpect(view().name("login")).andDo(print()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/creator/ProductCreator.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.creator; 2 | 3 | import com.syqu.shop.domain.Product; 4 | 5 | import java.math.BigDecimal; 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | 9 | public class ProductCreator { 10 | public static final String NAME = "Test"; 11 | public static final String DESCRIPTION = "testDescriptionTestDescription"; 12 | public static final BigDecimal PRICE = BigDecimal.valueOf(1000); 13 | public static final String IMAGE_URL = "https://avatars1.githubusercontent.com/u/30699233?s=400&u=cf0bc2b388b5c72364aaaedf26a8aab63f97ffcc&v=4"; 14 | 15 | public static Product createTestProduct(){ 16 | Product testProduct = new Product(); 17 | 18 | testProduct.setName(NAME); 19 | testProduct.setDescription(DESCRIPTION); 20 | testProduct.setPrice(PRICE); 21 | testProduct.setImageUrl(IMAGE_URL); 22 | 23 | return testProduct; 24 | } 25 | 26 | public static Set createTestProducts(){ 27 | Set testProducts = new HashSet<>(); 28 | 29 | testProducts.add(createTestProduct()); 30 | testProducts.add(createTestProduct()); 31 | testProducts.add(createTestProduct()); 32 | 33 | return testProducts; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/creator/UserCreator.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.creator; 2 | 3 | import com.syqu.shop.domain.User; 4 | 5 | import java.math.BigDecimal; 6 | 7 | public class UserCreator { 8 | public static final String USERNAME = "Test"; 9 | public static final String PASSWORD = "longpassword123"; 10 | public static final String FIRST_NAME = "Test"; 11 | public static final String LAST_NAME = "Test"; 12 | public static final int AGE = 23; 13 | public static final String EMAIL = "randomemail@gmail.test"; 14 | public static final String GENDER = "Male"; 15 | public static final BigDecimal BALANCE = new BigDecimal(1000); 16 | public static final String CITY = "Warsaw"; 17 | 18 | public static User createTestUser() { 19 | User testObject = new User(); 20 | 21 | testObject.setUsername(USERNAME); 22 | testObject.setPassword(PASSWORD); 23 | testObject.setPasswordConfirm(PASSWORD); 24 | testObject.setFirstName(FIRST_NAME); 25 | testObject.setLastName(LAST_NAME); 26 | testObject.setAge(AGE); 27 | testObject.setEmail(EMAIL); 28 | testObject.setGender(GENDER); 29 | testObject.setBalance(BALANCE); 30 | testObject.setCity(CITY); 31 | 32 | return testObject; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/model/ProductEntityTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.model; 2 | 3 | import com.syqu.shop.creator.ProductCreator; 4 | import com.syqu.shop.domain.Product; 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.rules.ExpectedException; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 11 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | import javax.persistence.PersistenceException; 16 | import javax.validation.ConstraintViolationException; 17 | 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest 20 | @DataJpaTest 21 | public class ProductEntityTests { 22 | @Rule 23 | public ExpectedException thrown = ExpectedException.none(); 24 | 25 | @Autowired 26 | private TestEntityManager entityManager; 27 | 28 | @Test 29 | public void createProductWhenNameIsNullShouldThrowException() { 30 | this.thrown.expect(ConstraintViolationException.class); 31 | this.thrown.expectMessage("must not be null"); 32 | 33 | Product testObject = ProductCreator.createTestProduct(); 34 | testObject.setName(null); 35 | 36 | entityManager.persistAndFlush(testObject); 37 | } 38 | 39 | @Test 40 | public void createProductWhenNameIsEmptyShouldThrowException() { 41 | this.thrown.expect(ConstraintViolationException.class); 42 | this.thrown.expectMessage("must not be empty"); 43 | 44 | Product testObject = ProductCreator.createTestProduct(); 45 | testObject.setName(""); 46 | 47 | entityManager.persistAndFlush(testObject); 48 | } 49 | 50 | @Test 51 | public void createProductWhenDescriptionIsNullShouldThrowException() { 52 | this.thrown.expect(ConstraintViolationException.class); 53 | this.thrown.expectMessage("must not be null"); 54 | 55 | Product testObject = ProductCreator.createTestProduct(); 56 | testObject.setDescription(null); 57 | 58 | entityManager.persistAndFlush(testObject); 59 | } 60 | 61 | @Test 62 | public void createProductWhenDescriptionIsEmptyShouldThrowException() { 63 | this.thrown.expect(ConstraintViolationException.class); 64 | this.thrown.expectMessage("must not be empty"); 65 | 66 | Product testObject = ProductCreator.createTestProduct(); 67 | testObject.setDescription(""); 68 | 69 | entityManager.persistAndFlush(testObject); 70 | } 71 | 72 | @Test 73 | public void createProductWhenDescriptionIsToLongShouldThrowException() { 74 | this.thrown.expect(PersistenceException.class); 75 | this.thrown.expectMessage("org.hibernate.exception.DataException: could not execute statement"); 76 | 77 | StringBuilder stringBuilder = new StringBuilder(); 78 | for (int i=0;i<101;i++){ 79 | stringBuilder.append("testtest"); 80 | } 81 | Product testObject = ProductCreator.createTestProduct(); 82 | testObject.setDescription(stringBuilder.toString()); 83 | 84 | entityManager.persistAndFlush(testObject); 85 | } 86 | 87 | @Test 88 | public void createProductWhenImageUrlIsNotValidUrlShouldThrowException() { 89 | this.thrown.expect(ConstraintViolationException.class); 90 | this.thrown.expectMessage("org.hibernate.validator.constraints.URL.message"); 91 | 92 | Product testObject = ProductCreator.createTestProduct(); 93 | testObject.setImageUrl("htt://test"); 94 | 95 | entityManager.persistAndFlush(testObject); 96 | } 97 | 98 | @Test 99 | public void createProductWhenPriceIsNullThrowException() { 100 | this.thrown.expect(ConstraintViolationException.class); 101 | this.thrown.expectMessage("must not be null"); 102 | 103 | Product testObject = ProductCreator.createTestProduct(); 104 | testObject.setPrice(null); 105 | 106 | entityManager.persistAndFlush(testObject); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/model/UserEntityTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.model; 2 | 3 | import com.syqu.shop.creator.UserCreator; 4 | import com.syqu.shop.domain.User; 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.rules.ExpectedException; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 11 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | import javax.validation.ConstraintViolationException; 16 | 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest 19 | @DataJpaTest 20 | public class UserEntityTests { 21 | @Rule 22 | public ExpectedException thrown = ExpectedException.none(); 23 | 24 | @Autowired 25 | private TestEntityManager entityManager; 26 | 27 | @Test 28 | public void createUserWhenUsernameIsNullShouldThrowException() { 29 | this.thrown.expect(ConstraintViolationException.class); 30 | this.thrown.expectMessage("must not be null"); 31 | 32 | User testObject = UserCreator.createTestUser(); 33 | testObject.setUsername(null); 34 | 35 | entityManager.persistAndFlush(testObject); 36 | } 37 | 38 | @Test 39 | public void createUserWhenUsernameIsEmptyShouldThrowException() { 40 | this.thrown.expect(ConstraintViolationException.class); 41 | this.thrown.expectMessage("must not be empty"); 42 | 43 | User testObject = UserCreator.createTestUser(); 44 | testObject.setUsername(""); 45 | 46 | entityManager.persistAndFlush(testObject); 47 | } 48 | 49 | @Test 50 | public void createUserWhenEmailIsEmptyShouldThrowException() { 51 | this.thrown.expect(ConstraintViolationException.class); 52 | this.thrown.expectMessage("must not be empty"); 53 | 54 | User testObject = UserCreator.createTestUser(); 55 | testObject.setEmail(""); 56 | 57 | entityManager.persistAndFlush(testObject); 58 | } 59 | 60 | @Test 61 | public void createUserWhenEmailHaveInvalidFormatShouldThrowException() { 62 | this.thrown.expect(ConstraintViolationException.class); 63 | this.thrown.expectMessage("must be a well-formed email address"); 64 | 65 | User testObject = UserCreator.createTestUser(); 66 | testObject.setEmail("syqu.pl"); 67 | 68 | entityManager.persistAndFlush(testObject); 69 | } 70 | 71 | @Test 72 | public void createUserWhenEmailIsNullShouldThrowException() { 73 | this.thrown.expect(ConstraintViolationException.class); 74 | this.thrown.expectMessage("must not be null"); 75 | 76 | User testObject = UserCreator.createTestUser(); 77 | testObject.setEmail(null); 78 | 79 | entityManager.persistAndFlush(testObject); 80 | } 81 | 82 | @Test 83 | public void createUserWhenPasswordIsNullShouldThrowException() { 84 | this.thrown.expect(ConstraintViolationException.class); 85 | this.thrown.expectMessage("must not be null"); 86 | 87 | User testObject = UserCreator.createTestUser(); 88 | testObject.setPassword(null); 89 | 90 | entityManager.persistAndFlush(testObject); 91 | } 92 | 93 | @Test 94 | public void createUserWhenPasswordIsEmptyShouldThrowException() { 95 | this.thrown.expect(ConstraintViolationException.class); 96 | this.thrown.expectMessage("must not be empty"); 97 | 98 | User testObject = UserCreator.createTestUser(); 99 | testObject.setPassword(""); 100 | 101 | entityManager.persistAndFlush(testObject); 102 | } 103 | 104 | @Test 105 | public void createUserWhenPasswordConfirmIsNullShouldThrowException() { 106 | this.thrown.expect(ConstraintViolationException.class); 107 | this.thrown.expectMessage("must not be null"); 108 | 109 | User testObject = UserCreator.createTestUser(); 110 | testObject.setPasswordConfirm(null); 111 | 112 | entityManager.persistAndFlush(testObject); 113 | } 114 | 115 | @Test 116 | public void createUserWhenPasswordConfirmIsEmptyShouldThrowException() { 117 | this.thrown.expect(ConstraintViolationException.class); 118 | this.thrown.expectMessage("must not be empty"); 119 | 120 | User testObject = UserCreator.createTestUser(); 121 | testObject.setPasswordConfirm(""); 122 | 123 | entityManager.persistAndFlush(testObject); 124 | } 125 | 126 | @Test 127 | public void createUserWhenGenderIsNullShouldThrowException() { 128 | this.thrown.expect(ConstraintViolationException.class); 129 | this.thrown.expectMessage("must not be null"); 130 | 131 | User testObject = UserCreator.createTestUser(); 132 | testObject.setGender(null); 133 | 134 | entityManager.persistAndFlush(testObject); 135 | } 136 | 137 | @Test 138 | public void createUserWhenGenderIsEmptyShouldThrowException() { 139 | this.thrown.expect(ConstraintViolationException.class); 140 | this.thrown.expectMessage("must not be empty"); 141 | 142 | User testObject = UserCreator.createTestUser(); 143 | testObject.setGender(""); 144 | 145 | entityManager.persistAndFlush(testObject); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/repository/ProductRepositoryTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.repository; 2 | 3 | import com.syqu.shop.creator.ProductCreator; 4 | import com.syqu.shop.domain.Product; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 9 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import java.util.List; 14 | import java.util.Random; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | 18 | @DataJpaTest 19 | @SpringBootTest 20 | @RunWith(SpringRunner.class) 21 | public class ProductRepositoryTests { 22 | 23 | @Autowired 24 | private TestEntityManager entityManager; 25 | 26 | @Autowired 27 | private ProductRepository productRepository; 28 | 29 | @Test 30 | public void checkIfProductRepositoryIsNotNull(){ 31 | assertThat(productRepository).isNotNull(); 32 | } 33 | 34 | @Test 35 | public void checkIfParamsAreTheSame(){ 36 | Product testObject = ProductCreator.createTestProduct(); 37 | entityManager.persistAndFlush(testObject); 38 | 39 | Product found = productRepository.findByName(testObject.getName()); 40 | 41 | assertThat(found.getId()).isEqualTo(testObject.getId()); 42 | assertThat(found.getName()).isEqualTo(testObject.getName()); 43 | assertThat(found.getDescription()).isEqualTo(testObject.getDescription()); 44 | assertThat(found.getPrice()).isEqualTo(testObject.getPrice()); 45 | assertThat(found.getImageUrl()).isEqualTo(testObject.getImageUrl()); 46 | } 47 | 48 | @Test 49 | public void whenFindByNameThenReturnProduct() { 50 | Product testObject = ProductCreator.createTestProduct(); 51 | entityManager.persistAndFlush(testObject); 52 | 53 | Product found = productRepository.findByName(testObject.getName()); 54 | assertThat(found.getName()).isEqualTo(testObject.getName()); 55 | } 56 | 57 | @Test 58 | public void whenFindByIdThenReturnProduct(){ 59 | Product testObject = ProductCreator.createTestProduct(); 60 | entityManager.persistAndFlush(testObject); 61 | 62 | Product found = productRepository.findById(testObject.getId()); 63 | assertThat(found.getId()).isEqualTo(testObject.getId()); 64 | } 65 | 66 | @Test 67 | public void whenFindAllByOrderByIdAscThenReturnAllProducts(){ 68 | Product testObject1 = ProductCreator.createTestProduct(); 69 | Product testObject2 = ProductCreator.createTestProduct(); 70 | Product testObject3 = ProductCreator.createTestProduct(); 71 | entityManager.persistAndFlush(testObject1); 72 | entityManager.persistAndFlush(testObject2); 73 | entityManager.persistAndFlush(testObject3); 74 | 75 | List found = productRepository.findAllByOrderByIdAsc(); 76 | assertThat(found.size()).isEqualTo(3); 77 | assertThat(found.get(0).getId()).isEqualTo(testObject1.getId()); 78 | assertThat(found.get(1).getId()).isEqualTo(testObject2.getId()); 79 | assertThat(found.get(2).getId()).isEqualTo(testObject3.getId()); 80 | } 81 | 82 | @Test 83 | public void whenFindByIdAndNoProductReturnNull(){ 84 | assertThat(productRepository.findById(new Random().nextLong())).isNull(); 85 | } 86 | 87 | @Test 88 | public void whenFindByNameAndNoProductReturnNull(){ 89 | assertThat(productRepository.findByName("random string")).isNull(); 90 | } 91 | 92 | @Test 93 | public void whenFindAllByOrderByIdAscAndNoProductsReturnNull(){ 94 | assertThat(productRepository.findAllByOrderByIdAsc()).isNullOrEmpty(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/repository/UserRepositoryTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.repository; 2 | 3 | import com.syqu.shop.creator.UserCreator; 4 | import com.syqu.shop.domain.User; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 9 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import java.util.Random; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | 17 | @DataJpaTest 18 | @SpringBootTest 19 | @RunWith(SpringRunner.class) 20 | public class UserRepositoryTests { 21 | 22 | @Autowired 23 | private TestEntityManager entityManager; 24 | 25 | @Autowired 26 | private UserRepository userRepository; 27 | 28 | @Test 29 | public void checkIfUserRepositoryIsNotNull(){ 30 | assertThat(userRepository).isNotNull(); 31 | } 32 | 33 | @Test 34 | public void checkIfParamsAreTheSame(){ 35 | User testObject = UserCreator.createTestUser(); 36 | entityManager.persistAndFlush(testObject); 37 | 38 | User found = userRepository.findByUsername(testObject.getUsername()); 39 | 40 | assertThat(found.getId()).isEqualTo(testObject.getId()); 41 | assertThat(found.getUsername()).isEqualTo(testObject.getUsername()); 42 | assertThat(found.getPassword()).isEqualTo(testObject.getPassword()); 43 | assertThat(found.getPasswordConfirm()).isEqualTo(found.getPassword()); 44 | assertThat(found.getPasswordConfirm()).isEqualTo(testObject.getPasswordConfirm()); 45 | assertThat(found.getFirstName()).isEqualTo(testObject.getFirstName()); 46 | assertThat(found.getLastName()).isEqualTo(testObject.getLastName()); 47 | assertThat(found.getEmail()).isEqualTo(testObject.getEmail()); 48 | assertThat(found.getAge()).isEqualTo(testObject.getAge()); 49 | assertThat(found.getBalance()).isEqualTo(testObject.getBalance()); 50 | assertThat(found.getCity()).isEqualTo(testObject.getCity()); 51 | assertThat(found.getGender()).isEqualTo(testObject.getGender()); 52 | } 53 | 54 | @Test 55 | public void whenFindByEmailThenReturnUser(){ 56 | User testObject = UserCreator.createTestUser(); 57 | 58 | entityManager.persistAndFlush(testObject); 59 | 60 | User found = userRepository.findByEmail(testObject.getEmail()); 61 | assertThat(found.getEmail()).isEqualTo(testObject.getEmail()); 62 | } 63 | 64 | @Test 65 | public void whenFindByIdThenReturnUser(){ 66 | User testObject = UserCreator.createTestUser(); 67 | 68 | entityManager.persistAndFlush(testObject); 69 | 70 | User found = userRepository.findById(testObject.getId()); 71 | assertThat(found.getId()).isEqualTo(testObject.getId()); 72 | } 73 | 74 | @Test 75 | public void whenFindByIdAndNoUserThenReturnNull() { 76 | assertThat(userRepository.findById(new Random().nextLong())).isNull(); 77 | } 78 | 79 | @Test 80 | public void whenFindByUsernameAndNoUserThenReturnNull() { 81 | assertThat(userRepository.findByUsername("xxminecraftplayerxx")).isNull(); 82 | } 83 | 84 | @Test 85 | public void whenFindByEmailAndNoUserThenReturnNull() { 86 | assertThat(userRepository.findByEmail("whatis@going.on")).isNull(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/service/ProductServiceTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service; 2 | 3 | import com.syqu.shop.creator.ProductCreator; 4 | import com.syqu.shop.domain.Product; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.mock.mockito.MockBean; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import java.math.BigDecimal; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | import static org.mockito.Mockito.when; 17 | import static org.mockito.MockitoAnnotations.initMocks; 18 | 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest 21 | public class ProductServiceTests { 22 | 23 | @MockBean 24 | private ProductService productService; 25 | 26 | @Test 27 | public void checkIfProductServiceIsNotNull(){ 28 | initMocks(this); 29 | 30 | assertThat(productService).isNotNull(); 31 | } 32 | @Test 33 | public void saveProductTests(){ 34 | Product product = ProductCreator.createTestProduct(); 35 | productService.save(product); 36 | when(productService.findById(product.getId())).thenReturn(product); 37 | Product found = productService.findById(product.getId()); 38 | 39 | assertThat(found).isNotNull(); 40 | assertThat(found.getName()).isEqualTo(product.getName()); 41 | assertThat(found.getDescription()).isEqualTo(product.getDescription()); 42 | assertThat(found.getPrice()).isEqualTo(product.getPrice()); 43 | assertThat(found.getImageUrl()).isEqualTo(product.getImageUrl()); 44 | } 45 | 46 | @Test 47 | public void editProductsTests(){ 48 | Product product = ProductCreator.createTestProduct(); 49 | Product newProduct = ProductCreator.createTestProduct(); 50 | newProduct.setName("Hello"); 51 | newProduct.setPrice(BigDecimal.valueOf(50)); 52 | newProduct.setDescription("Hello Description :)"); 53 | 54 | productService.save(product); 55 | productService.edit(product.getId(), newProduct); 56 | 57 | when(productService.findById(product.getId())).thenReturn(newProduct); 58 | Product found = productService.findById(newProduct.getId()); 59 | 60 | assertThat(found).isNotNull(); 61 | assertThat(found.getPrice()).isEqualTo(BigDecimal.valueOf(50)); 62 | assertThat(found.getName()).isEqualTo("Hello"); 63 | assertThat(found.getDescription()).isEqualTo("Hello Description :)"); 64 | } 65 | 66 | @Test 67 | public void deleteProductsTests(){ 68 | Product product = ProductCreator.createTestProduct(); 69 | productService.save(product); 70 | productService.delete(product.getId()); 71 | 72 | Product found = productService.findById(product.getId()); 73 | 74 | assertThat(found).isNull(); 75 | } 76 | 77 | @Test 78 | public void whenFindByIdThenReturnProduct(){ 79 | when(productService.findById(100L)).thenReturn(ProductCreator.createTestProduct()); 80 | Product found = productService.findById(100L); 81 | 82 | assertThat(found).isNotNull(); 83 | assertThat(found.getName()).isEqualTo(ProductCreator.NAME); 84 | assertThat(found.getDescription()).isEqualTo(ProductCreator.DESCRIPTION); 85 | assertThat(found.getPrice()).isEqualTo(ProductCreator.PRICE); 86 | assertThat(found.getImageUrl()).isEqualTo(ProductCreator.IMAGE_URL); 87 | } 88 | 89 | @Test 90 | public void whenFindAllByOrderByIdAscThenReturnAllProducts(){ 91 | ArrayList products = new ArrayList<>(ProductCreator.createTestProducts()); 92 | when(productService.findAllByOrderByIdAsc()).thenReturn(products); 93 | List found = productService.findAllByOrderByIdAsc(); 94 | 95 | assertThat(found).isNotNull(); 96 | for (Product product : found){ 97 | assertThat(product.getName()).isEqualTo(ProductCreator.NAME); 98 | assertThat(product.getDescription()).isEqualTo(ProductCreator.DESCRIPTION); 99 | assertThat(product.getPrice()).isEqualTo(ProductCreator.PRICE); 100 | assertThat(product.getImageUrl()).isEqualTo(ProductCreator.IMAGE_URL); 101 | } 102 | } 103 | 104 | @Test 105 | public void whenCountThenReturnProductsCount(){ 106 | when(productService.count()).thenReturn(3L); 107 | long count = productService.count(); 108 | 109 | assertThat(count).isNotNegative(); 110 | assertThat(count).isEqualTo(3L); 111 | 112 | } 113 | 114 | @Test 115 | public void whenFindByIdAndNoProductThenReturnNull(){ 116 | Product found = productService.findById(50L); 117 | 118 | assertThat(found).isNull(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/service/ShoppingCartServiceTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service; 2 | 3 | import com.syqu.shop.creator.ProductCreator; 4 | import com.syqu.shop.domain.Product; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.mock.mockito.MockBean; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import java.util.LinkedHashMap; 12 | import java.util.Map; 13 | 14 | import static org.assertj.core.api.Assertions.assertThat; 15 | import static org.mockito.Mockito.when; 16 | import static org.mockito.MockitoAnnotations.initMocks; 17 | 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest 20 | public class ShoppingCartServiceTests { 21 | 22 | @MockBean 23 | private ShoppingCartService shoppingCartService; 24 | 25 | @Test 26 | public void checkIfShoppingCartServiceIsNotNull() { 27 | initMocks(this); 28 | 29 | assertThat(shoppingCartService).isNotNull(); 30 | } 31 | 32 | @Test 33 | public void addProductToCartTests(){ 34 | Map cart = new LinkedHashMap<>(); 35 | Product product = ProductCreator.createTestProduct(); 36 | 37 | when(shoppingCartService.productsInCart()).thenReturn(cart); 38 | 39 | cart.put(product, 1); 40 | 41 | assertThat(shoppingCartService.productsInCart()).containsKey(product); 42 | } 43 | 44 | @Test 45 | public void addTwoTheSameProductsToCartTests(){ 46 | Map cart = new LinkedHashMap<>(); 47 | Product product = ProductCreator.createTestProduct(); 48 | Product product2 = ProductCreator.createTestProduct(); 49 | 50 | when(shoppingCartService.productsInCart()).thenReturn(cart); 51 | 52 | product.setName("Not Bad Trainers"); 53 | product2.setName("Nice Shoes"); 54 | 55 | cart.put(product, 1); 56 | cart.put(product2, 1); 57 | 58 | assertThat(shoppingCartService.productsInCart()).containsKey(product); 59 | assertThat(shoppingCartService.productsInCart()).containsKey(product2); 60 | } 61 | 62 | @Test 63 | public void removeProductFromCartTests(){ 64 | Map cart = new LinkedHashMap<>(); 65 | Product product = ProductCreator.createTestProduct(); 66 | 67 | when(shoppingCartService.productsInCart()).thenReturn(cart); 68 | 69 | cart.put(product, 1); 70 | assertThat(shoppingCartService.productsInCart()).containsKey(product); 71 | 72 | cart.remove(product); 73 | assertThat(shoppingCartService.productsInCart()).doesNotContainKey(product); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/syqu/shop/service/UserServiceTests.java: -------------------------------------------------------------------------------- 1 | package com.syqu.shop.service; 2 | 3 | import com.syqu.shop.creator.UserCreator; 4 | import com.syqu.shop.domain.User; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.mock.mockito.MockBean; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | import static org.mockito.Mockito.when; 13 | import static org.mockito.MockitoAnnotations.initMocks; 14 | 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest 17 | public class UserServiceTests { 18 | 19 | @MockBean 20 | private UserService userService; 21 | 22 | @Test 23 | public void checkIfUserServiceIsNotNull(){ 24 | initMocks(this); 25 | 26 | assertThat(userService).isNotNull(); 27 | } 28 | 29 | @Test 30 | public void saveUserTests(){ 31 | User user = UserCreator.createTestUser(); 32 | userService.save(user); 33 | when(userService.findById(user.getId())).thenReturn(user); 34 | User found = userService.findById(user.getId()); 35 | 36 | assertThat(found).isNotNull(); 37 | assertThat(found.getUsername()).isEqualTo(user.getUsername()); 38 | assertThat(found.getEmail()).isEqualTo(user.getEmail()); 39 | assertThat(found.getAge()).isEqualTo(user.getAge()); 40 | assertThat(found.getGender()).isEqualTo(user.getGender()); 41 | } 42 | 43 | @Test 44 | public void whenFindByIdThenReturnUser() { 45 | when(userService.findById(100L)).thenReturn(UserCreator.createTestUser()); 46 | User found = userService.findById(100L); 47 | 48 | assertThat(found).isNotNull(); 49 | assertThat(found.getUsername()).isEqualTo(UserCreator.USERNAME); 50 | assertThat(found.getEmail()).isEqualTo(UserCreator.EMAIL); 51 | assertThat(found.getAge()).isEqualTo(UserCreator.AGE); 52 | assertThat(found.getGender()).isEqualTo(UserCreator.GENDER); 53 | } 54 | 55 | @Test 56 | public void whenFindByUsernameThenReturnUser() { 57 | initMocks(this); 58 | 59 | when(userService.findByUsername(UserCreator.USERNAME)).thenReturn(UserCreator.createTestUser()); 60 | User found = userService.findByUsername(UserCreator.USERNAME); 61 | 62 | assertThat(found.getUsername()).isEqualTo(UserCreator.USERNAME); 63 | assertThat(found.getEmail()).isEqualTo(UserCreator.EMAIL); 64 | assertThat(found.getAge()).isEqualTo(UserCreator.AGE); 65 | assertThat(found.getGender()).isEqualTo(UserCreator.GENDER); 66 | } 67 | 68 | @Test 69 | public void whenFindByEmailThenReturnUser() { 70 | initMocks(this); 71 | 72 | when(userService.findByEmail(UserCreator.EMAIL)).thenReturn(UserCreator.createTestUser()); 73 | User found = userService.findByEmail(UserCreator.EMAIL); 74 | 75 | assertThat(found).isNotNull(); 76 | assertThat(found.getUsername()).isEqualTo(UserCreator.USERNAME); 77 | assertThat(found.getEmail()).isEqualTo(UserCreator.EMAIL); 78 | assertThat(found.getAge()).isEqualTo(UserCreator.AGE); 79 | assertThat(found.getGender()).isEqualTo(UserCreator.GENDER); 80 | } 81 | 82 | @Test 83 | public void whenFindByIdAndNoUserThenReturnNull(){ 84 | User found = userService.findById(25L); 85 | 86 | assertThat(found).isNull(); 87 | } 88 | 89 | @Test 90 | public void whenFindByUsernameAndNoUserThenReturnNull(){ 91 | User found = userService.findByUsername("Tests"); 92 | 93 | assertThat(found).isNull(); 94 | } 95 | 96 | @Test 97 | public void whenFindByEmailAndNoUserThenReturnNull(){ 98 | User found = userService.findByEmail("example@donut.org"); 99 | 100 | assertThat(found).isNull(); 101 | } 102 | } 103 | --------------------------------------------------------------------------------