├── .circleci
└── config.yml
├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
├── spring-command-pattern-entity
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── idspring
│ └── commandpattern
│ └── entity
│ ├── Cart.java
│ ├── CartItem.java
│ └── Product.java
├── spring-command-pattern-model
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── idspring
│ └── commandpattern
│ └── model
│ ├── controller
│ ├── CartAddProductRequest.java
│ ├── CartRemoveProductRequest.java
│ ├── CartUpdateProductRequest.java
│ └── Response.java
│ ├── package-info.java
│ └── service
│ ├── AddProductToCartRequest.java
│ ├── CreateNewCartRequest.java
│ ├── GetCartDetailRequest.java
│ ├── PingRequest.java
│ ├── RemoveProductFromCartRequest.java
│ ├── ServiceRequest.java
│ └── UpdateProductInCartRequest.java
├── spring-command-pattern-properties
├── pom.xml
└── src
│ └── main
│ └── resources
│ └── application.properties
├── spring-command-pattern-repository
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── idspring
│ │ └── commandpattern
│ │ └── repository
│ │ ├── CartRepository.java
│ │ └── ProductRepository.java
│ └── test
│ └── java
│ └── com
│ └── idspring
│ └── commandpattern
│ ├── SpringCommandPatternApplication.java
│ └── repository
│ ├── CartRepositoryTest.java
│ └── ProductRepositoryTest.java
├── spring-command-pattern-service
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── idspring
│ │ └── commandpattern
│ │ └── service
│ │ ├── AbstractCommand.java
│ │ ├── Command.java
│ │ ├── ServiceExecutor.java
│ │ ├── command
│ │ ├── AddProductToCartCommand.java
│ │ ├── CreateNewCartCommand.java
│ │ ├── GetCartDetailCommand.java
│ │ ├── PingCommand.java
│ │ ├── RemoveProductFromCartCommand.java
│ │ ├── UpdateProductInCartCommand.java
│ │ └── impl
│ │ │ ├── AddProductToCartCommandImpl.java
│ │ │ ├── CreateNewCartCommandImpl.java
│ │ │ ├── GetCartDetailCommandImpl.java
│ │ │ ├── PingCommandImpl.java
│ │ │ ├── RemoveProductFromCartCommandImpl.java
│ │ │ └── UpdateProductInCartCommandImpl.java
│ │ ├── exception
│ │ └── CommandValidationException.java
│ │ └── impl
│ │ └── ServiceExecutorImpl.java
│ └── test
│ └── java
│ └── com
│ └── idspring
│ └── commandpattern
│ ├── SpringCommandPatternApplication.java
│ └── service
│ ├── command
│ └── impl
│ │ ├── AddProductToCartCommandImplTest.java
│ │ ├── CreateNewCartCommandImplTest.java
│ │ ├── GetCartDetailCommandImplTest.java
│ │ ├── PingCommandImplTest.java
│ │ ├── RemoveProductFromCartCommandImplTest.java
│ │ └── UpdateProductInCartCommandImplTest.java
│ └── impl
│ └── ServiceExecutorImplTest.java
├── spring-command-pattern-validation
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── idspring
│ │ └── commandpattern
│ │ └── validation
│ │ ├── CartMustExists.java
│ │ ├── CartMustNotExists.java
│ │ ├── ProductMustExists.java
│ │ ├── ProductMustExistsInCart.java
│ │ ├── ProductQuantityMustEnough.java
│ │ ├── package-info.java
│ │ └── validator
│ │ ├── CartMustExistsValidator.java
│ │ ├── CartMustNotExistsValidator.java
│ │ ├── ProductMustExistsInCartValidator.java
│ │ ├── ProductMustExistsValidator.java
│ │ ├── ProductQuantityMustEnoughValidator.java
│ │ └── ProductQuantityUpdateMustEnoughValidator.java
│ └── test
│ └── java
│ └── com
│ └── idspring
│ └── commandpattern
│ ├── SpringCommandPatternApplication.java
│ └── validation
│ └── validator
│ ├── CartMustExistsValidatorTest.java
│ ├── CartMustNotExistsValidatorTest.java
│ ├── ProductMustExistsValidatorTest.java
│ └── ProductQuantityMustEnoughValidatorTest.java
└── spring-command-pattern-web
├── pom.xml
└── src
├── main
└── java
│ └── com
│ └── idspring
│ └── commandpattern
│ ├── SpringCommandPatternApplication.java
│ └── controller
│ ├── CartController.java
│ ├── ExceptionController.java
│ └── HomeController.java
└── test
└── java
└── com
└── idspring
└── commandpattern
└── controller
├── CartControllerTest.java
└── HomeControllerTest.java
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | docker:
5 | - image: maven:3-jdk-8
6 | working_directory: ~/repo
7 | environment:
8 | MAVEN_OPTS: -Xmx3200m
9 | steps:
10 | - checkout
11 | - run: mvn clean compile
12 |
13 | test:
14 | docker:
15 | - image: maven:3-jdk-8
16 | working_directory: ~/repo
17 | environment:
18 | MAVEN_OPTS: -Xmx3200m
19 | steps:
20 | - checkout
21 | - run: mvn clean test
22 |
23 | workflows:
24 | version: 2
25 | build_and_test:
26 | jobs:
27 | - build
28 | - test:
29 | requires:
30 | - build
--------------------------------------------------------------------------------
/.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 |
12 | ### IntelliJ IDEA ###
13 | .idea
14 | *.iws
15 | *.iml
16 | *.ipr
17 |
18 | ### NetBeans ###
19 | nbproject/private/
20 | build/
21 | nbbuild/
22 | dist/
23 | nbdist/
24 | .nb-gradle/
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/khannedy/spring-command-pattern/8cf14df4bb2525219ac4de330e62861362fa879d/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip
2 |
--------------------------------------------------------------------------------
/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.idspring
7 | command-pattern
8 | 0.0.1-SNAPSHOT
9 |
10 | spring-command-pattern-web
11 | spring-command-pattern-service
12 | spring-command-pattern-repository
13 | spring-command-pattern-entity
14 | spring-command-pattern-model
15 | spring-command-pattern-properties
16 | spring-command-pattern-validation
17 |
18 | pom
19 |
20 | spring-command-pattern
21 | Demo project for Spring Boot using Command Pattern
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-starter-parent
26 | 2.0.0.M2
27 |
28 |
29 |
30 |
31 | UTF-8
32 | UTF-8
33 | 1.8
34 |
35 |
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-starter-actuator
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-aop
44 |
45 |
46 | org.springframework.boot
47 | spring-boot-starter-data-mongodb-reactive
48 |
49 |
50 | org.springframework.boot
51 | spring-boot-starter-validation
52 |
53 |
54 | org.springframework.boot
55 | spring-boot-starter-webflux
56 |
57 |
58 | org.projectlombok
59 | lombok
60 | 1.16.16
61 |
62 |
63 | org.springframework.boot
64 | spring-boot-configuration-processor
65 | true
66 |
67 |
68 | org.springframework.boot
69 | spring-boot-starter-test
70 | test
71 |
72 |
73 | de.flapdoodle.embed
74 | de.flapdoodle.embed.mongo
75 | test
76 |
77 |
78 | io.rest-assured
79 | rest-assured
80 | 3.0.3
81 | test
82 |
83 |
84 |
85 |
86 |
87 | spring-snapshots
88 | Spring Snapshots
89 | https://repo.spring.io/snapshot
90 |
91 | true
92 |
93 |
94 |
95 | spring-milestones
96 | Spring Milestones
97 | https://repo.spring.io/milestone
98 |
99 | false
100 |
101 |
102 |
103 |
104 |
105 |
106 | spring-snapshots
107 | Spring Snapshots
108 | https://repo.spring.io/snapshot
109 |
110 | true
111 |
112 |
113 |
114 | spring-milestones
115 | Spring Milestones
116 | https://repo.spring.io/milestone
117 |
118 | false
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 | org.apache.maven.plugins
127 | maven-surefire-plugin
128 |
129 | false
130 |
131 |
132 |
133 |
134 |
135 |
136 |
--------------------------------------------------------------------------------
/spring-command-pattern-entity/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | command-pattern
7 | com.idspring
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | spring-command-pattern-entity
13 |
14 |
--------------------------------------------------------------------------------
/spring-command-pattern-entity/src/main/java/com/idspring/commandpattern/entity/Cart.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.entity;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 | import org.springframework.data.annotation.Id;
6 | import org.springframework.data.mongodb.core.mapping.Document;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 |
11 | /**
12 | * @author Eko Kurniawan Khannedy
13 | * @since 30/06/17
14 | */
15 | @Data
16 | @Builder
17 | @Document
18 | public class Cart {
19 |
20 | @Id
21 | private String id;
22 |
23 | private List items = new ArrayList<>();
24 |
25 | public List getItems() {
26 | if (items == null) {
27 | items = new ArrayList<>();
28 | }
29 | return items;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/spring-command-pattern-entity/src/main/java/com/idspring/commandpattern/entity/CartItem.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.entity;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | @Data
11 | @Builder
12 | public class CartItem {
13 |
14 | private String id;
15 |
16 | private String name;
17 |
18 | private Long price;
19 |
20 | private Integer quantity;
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/spring-command-pattern-entity/src/main/java/com/idspring/commandpattern/entity/Product.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.entity;
2 |
3 | import lombok.*;
4 | import org.springframework.data.annotation.Id;
5 | import org.springframework.data.mongodb.core.mapping.Document;
6 |
7 | /**
8 | * @author Eko Kurniawan Khannedy
9 | * @since 30/06/17
10 | */
11 | @Data
12 | @Builder
13 | @Document
14 | public class Product {
15 |
16 | @Id
17 | private String id;
18 |
19 | private String name;
20 |
21 | private Long price;
22 |
23 | private Integer stock;
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | command-pattern
7 | com.idspring
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | spring-command-pattern-model
13 |
14 |
15 |
16 | com.idspring
17 | spring-command-pattern-validation
18 | ${project.parent.version}
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/controller/CartAddProductRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.controller;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | @Data
11 | @Builder
12 | public class CartAddProductRequest {
13 |
14 | private String productId;
15 |
16 | private Integer quantity;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/controller/CartRemoveProductRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.controller;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 02/07/17
9 | */
10 | @Data
11 | @Builder
12 | public class CartRemoveProductRequest {
13 |
14 | private String productId;
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/controller/CartUpdateProductRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.controller;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 02/07/17
9 | */
10 | @Data
11 | @Builder
12 | public class CartUpdateProductRequest {
13 |
14 | private String productId;
15 |
16 | private Integer quantity;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/controller/Response.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.controller;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.lang.Nullable;
7 | import org.springframework.util.Assert;
8 |
9 | import java.util.*;
10 |
11 | /**
12 | * @author Eko Kurniawan Khannedy
13 | * @since 30/06/17
14 | */
15 | @Data
16 | @Builder
17 | public class Response {
18 |
19 | private Integer code;
20 |
21 | private String status;
22 |
23 | private T data;
24 |
25 | private Map> errors;
26 |
27 | public void addError(String key, String error) {
28 | initializeErrorsIfNull();
29 | initializeListIfNull(key);
30 |
31 | errors.get(key).add(error);
32 | }
33 |
34 | private void initializeErrorsIfNull() {
35 | if (errors == null) errors = new HashMap<>();
36 | }
37 |
38 | private void initializeListIfNull(String key) {
39 | errors.computeIfAbsent(key, k -> new ArrayList<>());
40 | }
41 |
42 | // ------------------------ STATIC --------------------------- //
43 |
44 | public static Response ok(T data) {
45 | Assert.notNull(data, "Data must not null");
46 | return Response.status(HttpStatus.OK, data);
47 | }
48 |
49 | public static Response okOrNotFound(@Nullable T data) {
50 | if (Objects.isNull(data)) {
51 | return Response.status(HttpStatus.NOT_FOUND, null);
52 | } else {
53 | return Response.ok(data);
54 | }
55 | }
56 |
57 | public static Response status(HttpStatus httpStatus, @Nullable T data) {
58 | return Response.builder()
59 | .code(httpStatus.value())
60 | .status(httpStatus.getReasonPhrase())
61 | .data(data)
62 | .build();
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Eko Kurniawan Khannedy
3 | * @since 30/06/17
4 | */
5 | package com.idspring.commandpattern.model;
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/service/AddProductToCartRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.service;
2 |
3 | import com.idspring.commandpattern.validation.CartMustExists;
4 | import com.idspring.commandpattern.validation.ProductMustExists;
5 | import com.idspring.commandpattern.validation.ProductQuantityMustEnough;
6 | import lombok.Builder;
7 | import lombok.Data;
8 | import org.hibernate.validator.constraints.NotBlank;
9 |
10 | import javax.validation.constraints.Max;
11 | import javax.validation.constraints.Min;
12 |
13 | /**
14 | * @author Eko Kurniawan Khannedy
15 | * @since 30/06/17
16 | */
17 | @Data
18 | @Builder
19 | @ProductQuantityMustEnough(path = "quantity")
20 | public class AddProductToCartRequest implements ServiceRequest, ProductQuantityMustEnough.ProductQuantity {
21 |
22 | @NotBlank
23 | @CartMustExists
24 | private String cartId;
25 |
26 | @NotBlank
27 | @ProductMustExists
28 | private String productId;
29 |
30 | @Min(1)
31 | @Max(10)
32 | private Integer quantity;
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/service/CreateNewCartRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.service;
2 |
3 | import com.idspring.commandpattern.validation.CartMustNotExists;
4 | import lombok.Builder;
5 | import lombok.Data;
6 |
7 | /**
8 | * @author Eko Kurniawan Khannedy
9 | * @since 01/07/17
10 | */
11 | @Data
12 | @Builder
13 | public class CreateNewCartRequest implements ServiceRequest {
14 |
15 | @CartMustNotExists
16 | private String cartId;
17 | }
18 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/service/GetCartDetailRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.service;
2 |
3 | import com.idspring.commandpattern.validation.CartMustExists;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import org.hibernate.validator.constraints.NotBlank;
7 |
8 | /**
9 | * @author Eko Kurniawan Khannedy
10 | * @since 01/07/17
11 | */
12 | @Data
13 | @Builder
14 | public class GetCartDetailRequest implements ServiceRequest {
15 |
16 | @NotBlank
17 | @CartMustExists
18 | private String cartId;
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/service/PingRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.service;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | @Data
11 | @Builder
12 | public class PingRequest implements ServiceRequest {
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/service/RemoveProductFromCartRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.service;
2 |
3 | import com.idspring.commandpattern.validation.CartMustExists;
4 | import com.idspring.commandpattern.validation.ProductMustExists;
5 | import com.idspring.commandpattern.validation.ProductMustExistsInCart;
6 | import lombok.Builder;
7 | import lombok.Data;
8 | import org.hibernate.validator.constraints.NotBlank;
9 |
10 | /**
11 | * @author Eko Kurniawan Khannedy
12 | * @since 02/07/17
13 | */
14 | @Data
15 | @Builder
16 | @ProductMustExistsInCart(path = "productId")
17 | public class RemoveProductFromCartRequest implements ServiceRequest,
18 | ProductMustExistsInCart.ProductInCart {
19 |
20 | @NotBlank
21 | @CartMustExists
22 | private String cartId;
23 |
24 | @NotBlank
25 | @ProductMustExists
26 | private String productId;
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/service/ServiceRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.service;
2 |
3 | /**
4 | * @author Eko Kurniawan Khannedy
5 | * @since 30/06/17
6 | */
7 | public interface ServiceRequest {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/spring-command-pattern-model/src/main/java/com/idspring/commandpattern/model/service/UpdateProductInCartRequest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.model.service;
2 |
3 | import com.idspring.commandpattern.validation.CartMustExists;
4 | import com.idspring.commandpattern.validation.ProductMustExists;
5 | import com.idspring.commandpattern.validation.ProductMustExistsInCart;
6 | import com.idspring.commandpattern.validation.ProductQuantityMustEnough;
7 | import lombok.Builder;
8 | import lombok.Data;
9 | import org.hibernate.validator.constraints.NotBlank;
10 |
11 | import javax.validation.constraints.Max;
12 | import javax.validation.constraints.Min;
13 |
14 | /**
15 | * @author Eko Kurniawan Khannedy
16 | * @since 01/07/17
17 | */
18 | @Data
19 | @Builder
20 | @ProductMustExistsInCart(path = "productId")
21 | @ProductQuantityMustEnough(path = "quantity")
22 | public class UpdateProductInCartRequest implements
23 | ProductQuantityMustEnough.ProductQuantityUpdate,
24 | ProductMustExistsInCart.ProductInCart,
25 | ServiceRequest {
26 |
27 | @NotBlank
28 | @CartMustExists
29 | private String cartId;
30 |
31 | @NotBlank
32 | @ProductMustExists
33 | private String productId;
34 |
35 | @Min(0)
36 | @Max(10)
37 | private Integer quantity;
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/spring-command-pattern-properties/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | command-pattern
7 | com.idspring
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | spring-command-pattern-properties
13 |
14 |
--------------------------------------------------------------------------------
/spring-command-pattern-properties/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.application.name=spring-command-pattern
2 |
3 | spring.data.mongodb.host=localhost
4 | spring.data.mongodb.port=27017
5 | spring.data.mongodb.database=spring-command-pattern
6 |
--------------------------------------------------------------------------------
/spring-command-pattern-repository/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | command-pattern
7 | com.idspring
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | spring-command-pattern-repository
13 |
14 |
15 |
16 | com.idspring
17 | spring-command-pattern-entity
18 | ${project.parent.version}
19 |
20 |
21 | com.idspring
22 | spring-command-pattern-properties
23 | ${project.parent.version}
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/spring-command-pattern-repository/src/main/java/com/idspring/commandpattern/repository/CartRepository.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.repository;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | public interface CartRepository extends ReactiveMongoRepository {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/spring-command-pattern-repository/src/main/java/com/idspring/commandpattern/repository/ProductRepository.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.repository;
2 |
3 | import com.idspring.commandpattern.entity.Product;
4 | import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | public interface ProductRepository extends ReactiveMongoRepository {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/spring-command-pattern-repository/src/test/java/com/idspring/commandpattern/SpringCommandPatternApplication.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern;
2 |
3 | import org.springframework.boot.autoconfigure.SpringBootApplication;
4 |
5 | @SpringBootApplication
6 | public class SpringCommandPatternApplication {
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/spring-command-pattern-repository/src/test/java/com/idspring/commandpattern/repository/CartRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.repository;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.CartItem;
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.context.SpringBootTest;
9 | import org.springframework.test.annotation.DirtiesContext;
10 | import org.springframework.test.context.junit4.SpringRunner;
11 |
12 | import java.util.Arrays;
13 |
14 | import static org.junit.Assert.*;
15 |
16 | /**
17 | * @author Eko Kurniawan Khannedy
18 | * @since 30/06/17
19 | */
20 | @RunWith(SpringRunner.class)
21 | @SpringBootTest
22 | @DirtiesContext
23 | public class CartRepositoryTest {
24 |
25 | @Autowired
26 | private CartRepository cartRepository;
27 |
28 | @Test
29 | public void testSaveCart() throws Exception {
30 | Cart cart = Cart.builder()
31 | .id("id")
32 | .items(Arrays.asList(
33 | CartItem.builder()
34 | .id("1")
35 | .name("Mie Ayam Goreng")
36 | .price(1000L)
37 | .quantity(10)
38 | .build(),
39 | CartItem.builder()
40 | .id("1")
41 | .name("Mie Ayam Rebus")
42 | .price(500L)
43 | .quantity(5)
44 | .build()
45 | ))
46 | .build();
47 |
48 | Cart result = cartRepository.save(cart).block();
49 |
50 | assertEquals(cart, result);
51 | }
52 |
53 | @Test
54 | public void testSaveAndGetCart() throws Exception {
55 | Cart cart = Cart.builder()
56 | .id("id")
57 | .items(Arrays.asList(
58 | CartItem.builder()
59 | .id("1")
60 | .name("Mie Ayam Goreng")
61 | .price(1000L)
62 | .quantity(10)
63 | .build(),
64 | CartItem.builder()
65 | .id("1")
66 | .name("Mie Ayam Rebus")
67 | .price(500L)
68 | .quantity(5)
69 | .build()
70 | ))
71 | .build();
72 |
73 | cartRepository.save(cart).block();
74 | Cart result = cartRepository.findById(cart.getId()).block();
75 |
76 | assertEquals(cart, result);
77 | }
78 | }
--------------------------------------------------------------------------------
/spring-command-pattern-repository/src/test/java/com/idspring/commandpattern/repository/ProductRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.repository;
2 |
3 | import com.idspring.commandpattern.entity.Product;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.test.annotation.DirtiesContext;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * @author Eko Kurniawan Khannedy
15 | * @since 30/06/17
16 | */
17 | @RunWith(SpringRunner.class)
18 | @SpringBootTest
19 | @DirtiesContext
20 | public class ProductRepositoryTest {
21 |
22 | @Autowired
23 | private ProductRepository productRepository;
24 |
25 | @Test
26 | public void testSaveProduct() throws Exception {
27 | Product product = Product.builder()
28 | .id("id")
29 | .name("name")
30 | .price(1000L)
31 | .stock(1000)
32 | .build();
33 |
34 | Product result = productRepository.save(product).block();
35 |
36 | assertEquals(result, product);
37 | }
38 |
39 | @Test
40 | public void testSaveAndGetProduct() throws Exception {
41 | Product product = Product.builder()
42 | .id("id")
43 | .name("name")
44 | .price(1000L)
45 | .stock(1000)
46 | .build();
47 |
48 | productRepository.save(product).block();
49 | Product result = productRepository.findById("id").block();
50 |
51 | assertEquals(result, product);
52 | }
53 | }
--------------------------------------------------------------------------------
/spring-command-pattern-service/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | command-pattern
7 | com.idspring
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | spring-command-pattern-service
13 |
14 |
15 |
16 | com.idspring
17 | spring-command-pattern-model
18 | ${project.parent.version}
19 |
20 |
21 | com.idspring
22 | spring-command-pattern-repository
23 | ${project.parent.version}
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/AbstractCommand.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service;
2 |
3 | import com.idspring.commandpattern.model.service.ServiceRequest;
4 | import com.idspring.commandpattern.service.exception.CommandValidationException;
5 | import org.springframework.beans.BeansException;
6 | import org.springframework.beans.factory.InitializingBean;
7 | import org.springframework.context.ApplicationContext;
8 | import org.springframework.context.ApplicationContextAware;
9 | import reactor.core.publisher.Mono;
10 |
11 | import javax.validation.ConstraintViolation;
12 | import javax.validation.Validator;
13 | import java.util.Set;
14 |
15 | /**
16 | * @author Eko Kurniawan Khannedy
17 | * @since 30/06/17
18 | */
19 | public abstract class AbstractCommand
20 | implements Command, ApplicationContextAware, InitializingBean {
21 |
22 | protected Validator validator;
23 |
24 | protected ApplicationContext applicationContext;
25 |
26 | @Override
27 | public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
28 | this.applicationContext = applicationContext;
29 | }
30 |
31 | @Override
32 | public final void afterPropertiesSet() throws Exception {
33 | this.validator = applicationContext.getBean(Validator.class);
34 | }
35 |
36 | @Override
37 | public final Mono execute(REQUEST request) {
38 | Set> constraintViolations = validator.validate(request);
39 | if (constraintViolations.isEmpty()) {
40 | return doExecute(request);
41 | } else {
42 | return Mono.error(new CommandValidationException(constraintViolations));
43 | }
44 | }
45 |
46 | public abstract Mono doExecute(REQUEST request);
47 | }
48 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/Command.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service;
2 |
3 | import com.idspring.commandpattern.model.service.ServiceRequest;
4 | import reactor.core.publisher.Mono;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | public interface Command {
11 |
12 | Mono execute(REQUEST request);
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/ServiceExecutor.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service;
2 |
3 | import com.idspring.commandpattern.model.service.ServiceRequest;
4 | import reactor.core.publisher.Mono;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | public interface ServiceExecutor {
11 |
12 | Mono execute(Class extends Command> commandClass, R request);
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/AddProductToCartCommand.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.AddProductToCartRequest;
5 | import com.idspring.commandpattern.service.Command;
6 |
7 | /**
8 | * @author Eko Kurniawan Khannedy
9 | * @since 30/06/17
10 | */
11 | public interface AddProductToCartCommand extends Command {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/CreateNewCartCommand.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.CreateNewCartRequest;
5 | import com.idspring.commandpattern.service.Command;
6 |
7 | /**
8 | * @author Eko Kurniawan Khannedy
9 | * @since 01/07/17
10 | */
11 | public interface CreateNewCartCommand extends Command {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/GetCartDetailCommand.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.GetCartDetailRequest;
5 | import com.idspring.commandpattern.service.Command;
6 |
7 | /**
8 | * @author Eko Kurniawan Khannedy
9 | * @since 01/07/17
10 | */
11 | public interface GetCartDetailCommand extends Command {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/PingCommand.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command;
2 |
3 | import com.idspring.commandpattern.model.service.ServiceRequest;
4 | import com.idspring.commandpattern.service.Command;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | public interface PingCommand extends Command {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/RemoveProductFromCartCommand.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.RemoveProductFromCartRequest;
5 | import com.idspring.commandpattern.service.Command;
6 |
7 | /**
8 | * @author Eko Kurniawan Khannedy
9 | * @since 02/07/17
10 | */
11 | public interface RemoveProductFromCartCommand extends Command {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/UpdateProductInCartCommand.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.UpdateProductInCartRequest;
5 | import com.idspring.commandpattern.service.Command;
6 |
7 | /**
8 | * @author Eko Kurniawan Khannedy
9 | * @since 01/07/17
10 | */
11 | public interface UpdateProductInCartCommand extends Command {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/impl/AddProductToCartCommandImpl.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.CartItem;
5 | import com.idspring.commandpattern.entity.Product;
6 | import com.idspring.commandpattern.model.service.AddProductToCartRequest;
7 | import com.idspring.commandpattern.repository.CartRepository;
8 | import com.idspring.commandpattern.repository.ProductRepository;
9 | import com.idspring.commandpattern.service.AbstractCommand;
10 | import com.idspring.commandpattern.service.command.AddProductToCartCommand;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.stereotype.Component;
13 | import reactor.core.publisher.Mono;
14 |
15 | /**
16 | * @author Eko Kurniawan Khannedy
17 | * @since 30/06/17
18 | */
19 | @Component
20 | public class AddProductToCartCommandImpl extends AbstractCommand
21 | implements AddProductToCartCommand {
22 |
23 | @Autowired
24 | private ProductRepository productRepository;
25 |
26 | @Autowired
27 | private CartRepository cartRepository;
28 |
29 | @Override
30 | public Mono doExecute(AddProductToCartRequest request) {
31 | return Mono.zip(
32 | objects -> addOrUpdateProductInCart((Cart) objects[0], (Product) objects[1], request.getQuantity()),
33 | cartRepository.findById(request.getCartId()),
34 | productRepository.findById(request.getProductId())
35 | ).flatMap(cart -> cartRepository.save(cart));
36 | }
37 |
38 | private Cart addOrUpdateProductInCart(Cart cart, Product product, Integer quantity) {
39 | if (isCartContainProduct(cart, product)) {
40 | incrementProductQuantity(cart, product, quantity);
41 | } else {
42 | addNewProductToCart(cart, product, quantity);
43 | }
44 |
45 | return cart;
46 | }
47 |
48 | private boolean isCartContainProduct(Cart cart, Product product) {
49 | return cart.getItems().stream()
50 | .anyMatch(cartItem -> cartItem.getId().equals(product.getId()));
51 | }
52 |
53 | private void incrementProductQuantity(Cart cart, Product product, Integer quantity) {
54 | cart.getItems().stream()
55 | .filter(cartItem -> cartItem.getId().equals(product.getId()))
56 | .forEach(cartItem -> cartItem.setQuantity(cartItem.getQuantity() + quantity));
57 | }
58 |
59 | private void addNewProductToCart(Cart cart, Product product, Integer quantity) {
60 | CartItem item = CartItem.builder()
61 | .id(product.getId())
62 | .name(product.getName())
63 | .price(product.getPrice())
64 | .quantity(quantity)
65 | .build();
66 |
67 | cart.getItems().add(item);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/impl/CreateNewCartCommandImpl.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.CreateNewCartRequest;
5 | import com.idspring.commandpattern.repository.CartRepository;
6 | import com.idspring.commandpattern.service.AbstractCommand;
7 | import com.idspring.commandpattern.service.command.CreateNewCartCommand;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.stereotype.Component;
10 | import reactor.core.publisher.Mono;
11 |
12 | /**
13 | * @author Eko Kurniawan Khannedy
14 | * @since 01/07/17
15 | */
16 | @Component
17 | public class CreateNewCartCommandImpl extends AbstractCommand
18 | implements CreateNewCartCommand {
19 |
20 | @Autowired
21 | private CartRepository cartRepository;
22 |
23 | @Override
24 | public Mono doExecute(CreateNewCartRequest request) {
25 | Cart cart = newCart(request.getCartId());
26 | return cartRepository.save(cart);
27 | }
28 |
29 | private Cart newCart(String id) {
30 | return Cart.builder()
31 | .id(id)
32 | .build();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/impl/GetCartDetailCommandImpl.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.GetCartDetailRequest;
5 | import com.idspring.commandpattern.repository.CartRepository;
6 | import com.idspring.commandpattern.service.AbstractCommand;
7 | import com.idspring.commandpattern.service.command.GetCartDetailCommand;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.stereotype.Component;
10 | import reactor.core.publisher.Mono;
11 |
12 | /**
13 | * @author Eko Kurniawan Khannedy
14 | * @since 01/07/17
15 | */
16 | @Component
17 | public class GetCartDetailCommandImpl extends AbstractCommand
18 | implements GetCartDetailCommand {
19 |
20 | @Autowired
21 | private CartRepository cartRepository;
22 |
23 | @Override
24 | public Mono doExecute(GetCartDetailRequest request) {
25 | return cartRepository.findById(request.getCartId());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/impl/PingCommandImpl.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.model.service.ServiceRequest;
4 | import com.idspring.commandpattern.service.AbstractCommand;
5 | import com.idspring.commandpattern.service.command.PingCommand;
6 | import org.springframework.stereotype.Component;
7 | import reactor.core.publisher.Mono;
8 |
9 | /**
10 | * @author Eko Kurniawan Khannedy
11 | * @since 30/06/17
12 | */
13 | @Component
14 | public class PingCommandImpl extends AbstractCommand implements PingCommand {
15 |
16 | @Override
17 | public Mono doExecute(ServiceRequest request) {
18 | return Mono.just("Pong");
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/impl/RemoveProductFromCartCommandImpl.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.CartItem;
5 | import com.idspring.commandpattern.model.service.RemoveProductFromCartRequest;
6 | import com.idspring.commandpattern.repository.CartRepository;
7 | import com.idspring.commandpattern.service.AbstractCommand;
8 | import com.idspring.commandpattern.service.command.RemoveProductFromCartCommand;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.stereotype.Component;
11 | import reactor.core.publisher.Mono;
12 |
13 | /**
14 | * @author Eko Kurniawan Khannedy
15 | * @since 02/07/17
16 | */
17 | @Component
18 | public class RemoveProductFromCartCommandImpl extends AbstractCommand
19 | implements RemoveProductFromCartCommand {
20 |
21 | @Autowired
22 | private CartRepository cartRepository;
23 |
24 | @Override
25 | public Mono doExecute(RemoveProductFromCartRequest request) {
26 | return cartRepository.findById(request.getCartId())
27 | .map(cart -> findCartItemAndRemoveIt(cart, request.getProductId()))
28 | .flatMap(cart -> cartRepository.save(cart));
29 | }
30 |
31 | private Cart findCartItemAndRemoveIt(Cart cart, String productId) {
32 | CartItem cartItem = findItemInCart(cart, productId);
33 | return removeItemFromCart(cart, cartItem);
34 | }
35 |
36 | private CartItem findItemInCart(Cart cart, String productId) {
37 | return cart.getItems().stream()
38 | .filter(cartItem -> cartItem.getId().equals(productId))
39 | .findFirst().get();
40 | }
41 |
42 | private Cart removeItemFromCart(Cart cart, CartItem cartItem) {
43 | cart.getItems().remove(cartItem);
44 | return cart;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/command/impl/UpdateProductInCartCommandImpl.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.UpdateProductInCartRequest;
5 | import com.idspring.commandpattern.repository.CartRepository;
6 | import com.idspring.commandpattern.service.AbstractCommand;
7 | import com.idspring.commandpattern.service.command.UpdateProductInCartCommand;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.stereotype.Component;
10 | import reactor.core.publisher.Mono;
11 |
12 | /**
13 | * @author Eko Kurniawan Khannedy
14 | * @since 01/07/17
15 | */
16 | @Component
17 | public class UpdateProductInCartCommandImpl extends AbstractCommand
18 | implements UpdateProductInCartCommand {
19 |
20 | @Autowired
21 | private CartRepository cartRepository;
22 |
23 | @Override
24 | public Mono doExecute(UpdateProductInCartRequest request) {
25 | return cartRepository.findById(request.getCartId())
26 | .map(cart -> updateCartItemQuantity(cart, request));
27 | }
28 |
29 | private Cart updateCartItemQuantity(Cart cart, UpdateProductInCartRequest request) {
30 | cart.getItems().stream()
31 | .filter(cartItem -> cartItem.getId().equals(request.getProductId()))
32 | .forEach(cartItem -> cartItem.setQuantity(cartItem.getQuantity() + request.getQuantity()));
33 |
34 | return cart;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/exception/CommandValidationException.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.exception;
2 |
3 | import javax.validation.ConstraintViolation;
4 | import java.util.Set;
5 |
6 | /**
7 | * @author Eko Kurniawan Khannedy
8 | * @since 30/06/17
9 | */
10 | public class CommandValidationException extends RuntimeException {
11 |
12 | private Set> constraintViolations;
13 |
14 | @SuppressWarnings("unchecked")
15 | public CommandValidationException(Set constraintViolations) {
16 | this.constraintViolations = (Set>) constraintViolations;
17 | }
18 |
19 | public Set> getConstraintViolations() {
20 | return constraintViolations;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/main/java/com/idspring/commandpattern/service/impl/ServiceExecutorImpl.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.impl;
2 |
3 | import com.idspring.commandpattern.model.service.ServiceRequest;
4 | import com.idspring.commandpattern.service.Command;
5 | import com.idspring.commandpattern.service.ServiceExecutor;
6 | import org.springframework.beans.BeansException;
7 | import org.springframework.context.ApplicationContext;
8 | import org.springframework.context.ApplicationContextAware;
9 | import org.springframework.stereotype.Component;
10 | import reactor.core.publisher.Mono;
11 |
12 | /**
13 | * @author Eko Kurniawan Khannedy
14 | * @since 30/06/17
15 | */
16 | @Component
17 | public class ServiceExecutorImpl implements ServiceExecutor, ApplicationContextAware {
18 |
19 | private ApplicationContext applicationContext;
20 |
21 | @Override
22 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
23 | this.applicationContext = applicationContext;
24 | }
25 |
26 | @Override
27 | public Mono execute(Class extends Command> commandClass, R request) {
28 | Command command = applicationContext.getBean(commandClass);
29 | return command.execute(request);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/SpringCommandPatternApplication.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern;
2 |
3 | import org.springframework.boot.autoconfigure.SpringBootApplication;
4 |
5 | @SpringBootApplication
6 | public class SpringCommandPatternApplication {
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/service/command/impl/AddProductToCartCommandImplTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.CartItem;
5 | import com.idspring.commandpattern.entity.Product;
6 | import com.idspring.commandpattern.model.service.AddProductToCartRequest;
7 | import com.idspring.commandpattern.repository.CartRepository;
8 | import com.idspring.commandpattern.repository.ProductRepository;
9 | import com.idspring.commandpattern.service.command.AddProductToCartCommand;
10 | import com.idspring.commandpattern.service.exception.CommandValidationException;
11 | import org.junit.Test;
12 | import org.junit.runner.RunWith;
13 | import org.springframework.beans.factory.annotation.Autowired;
14 | import org.springframework.boot.test.context.SpringBootTest;
15 | import org.springframework.test.annotation.DirtiesContext;
16 | import org.springframework.test.context.junit4.SpringRunner;
17 |
18 | import javax.validation.ConstraintViolation;
19 | import java.util.Collections;
20 | import java.util.List;
21 | import java.util.stream.Collectors;
22 |
23 | import static org.junit.Assert.*;
24 | import static org.hamcrest.Matchers.*;
25 |
26 | /**
27 | * @author Eko Kurniawan Khannedy
28 | * @since 30/06/17
29 | */
30 | @RunWith(SpringRunner.class)
31 | @SpringBootTest
32 | @DirtiesContext
33 | public class AddProductToCartCommandImplTest {
34 |
35 | @Autowired
36 | private AddProductToCartCommand command;
37 |
38 | @Autowired
39 | private CartRepository cartRepository;
40 |
41 | @Autowired
42 | private ProductRepository productRepository;
43 |
44 | private void createCart(String id) {
45 | Cart cart = Cart.builder()
46 | .id(id)
47 | .build();
48 | cartRepository.save(cart).block();
49 | }
50 |
51 | private void createProduct(String id) {
52 | Product product = Product.builder()
53 | .id(id)
54 | .name("Product Name")
55 | .price(1000L)
56 | .stock(100)
57 | .build();
58 | productRepository.save(product).block();
59 | }
60 |
61 | @Test
62 | public void testAddProductToNonExistsCart() throws Exception {
63 | String cartId = "not-exists";
64 | String productId = "sample-product-id";
65 |
66 | createProduct(productId);
67 |
68 | AddProductToCartRequest request = AddProductToCartRequest.builder()
69 | .cartId(cartId)
70 | .productId(productId)
71 | .quantity(10)
72 | .build();
73 |
74 | try {
75 | command.execute(request).block();
76 | fail("it should thrown exception");
77 | } catch (CommandValidationException ex) {
78 | List messages = ex.getConstraintViolations().stream()
79 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
80 | assertThat(messages, hasItems("CartMustExists"));
81 | }
82 | }
83 |
84 | @Test
85 | public void testAddProductToEmptyCart() throws Exception {
86 | String cartId = "sample-cart-id";
87 | String productId = "sample-product-id";
88 |
89 | createCart(cartId);
90 | createProduct(productId);
91 |
92 | AddProductToCartRequest request = AddProductToCartRequest.builder()
93 | .cartId(cartId)
94 | .productId(productId)
95 | .quantity(10)
96 | .build();
97 |
98 | Cart result = command.execute(request).block();
99 | Cart expected = Cart.builder()
100 | .id(cartId)
101 | .items(Collections.singletonList(
102 | CartItem.builder()
103 | .id(productId)
104 | .name("Product Name")
105 | .price(1000L)
106 | .quantity(10)
107 | .build()
108 | ))
109 | .build();
110 |
111 | assertThat(result, equalTo(expected));
112 | }
113 |
114 | @Test
115 | public void testIncrementProductQuantityInCart() throws Exception {
116 | testAddProductToEmptyCart();
117 |
118 | String cartId = "sample-cart-id";
119 | String productId = "sample-product-id";
120 |
121 | AddProductToCartRequest request = AddProductToCartRequest.builder()
122 | .cartId(cartId)
123 | .productId(productId)
124 | .quantity(10)
125 | .build();
126 |
127 | Cart result = command.execute(request).block();
128 | Cart expected = Cart.builder()
129 | .id(cartId)
130 | .items(Collections.singletonList(
131 | CartItem.builder()
132 | .id(productId)
133 | .name("Product Name")
134 | .price(1000L)
135 | .quantity(20)
136 | .build()
137 | ))
138 | .build();
139 |
140 | assertThat(result, equalTo(expected));
141 | }
142 | }
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/service/command/impl/CreateNewCartCommandImplTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.CreateNewCartRequest;
5 | import com.idspring.commandpattern.repository.CartRepository;
6 | import com.idspring.commandpattern.service.exception.CommandValidationException;
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.test.annotation.DirtiesContext;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 |
14 | import static org.junit.Assert.*;
15 |
16 | /**
17 | * @author Eko Kurniawan Khannedy
18 | * @since 01/07/17
19 | */
20 | @RunWith(SpringRunner.class)
21 | @SpringBootTest
22 | @DirtiesContext
23 | public class CreateNewCartCommandImplTest {
24 |
25 | @Autowired
26 | private CartRepository cartRepository;
27 |
28 | @Autowired
29 | private CreateNewCartCommandImpl command;
30 |
31 | private void createCart(String id) {
32 | Cart cart = Cart.builder()
33 | .id(id)
34 | .build();
35 |
36 | cartRepository.save(cart).block();
37 | }
38 |
39 | @Test
40 | public void testSuccessCreateCart() throws Exception {
41 | String cartId = "not-exists-cart-id";
42 | CreateNewCartRequest request = CreateNewCartRequest.builder()
43 | .cartId(cartId)
44 | .build();
45 |
46 | Cart cart = command.execute(request).block();
47 | Cart dbCart = cartRepository.findById(cartId).block();
48 |
49 | assertEquals(dbCart, cart);
50 | }
51 |
52 | @Test
53 | public void testFailedCartAlreadyExists() throws Throwable {
54 | String cartId = "exists-cart";
55 | createCart(cartId);
56 |
57 | CreateNewCartRequest request = CreateNewCartRequest.builder()
58 | .cartId(cartId)
59 | .build();
60 |
61 | try {
62 | command.execute(request).block();
63 | fail("It should be throw exception");
64 | } catch (CommandValidationException e) {
65 | e.getConstraintViolations().forEach(constraintViolation ->
66 | assertEquals("CartMustNotExists", constraintViolation.getMessage())
67 | );
68 | }
69 | }
70 | }
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/service/command/impl/GetCartDetailCommandImplTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.service.GetCartDetailRequest;
5 | import com.idspring.commandpattern.repository.CartRepository;
6 | import com.idspring.commandpattern.service.exception.CommandValidationException;
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.test.annotation.DirtiesContext;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 |
14 | import static org.junit.Assert.*;
15 |
16 | /**
17 | * @author Eko Kurniawan Khannedy
18 | * @since 01/07/17
19 | */
20 | @RunWith(SpringRunner.class)
21 | @SpringBootTest
22 | @DirtiesContext
23 | public class GetCartDetailCommandImplTest {
24 |
25 | @Autowired
26 | private CartRepository cartRepository;
27 |
28 | @Autowired
29 | private GetCartDetailCommandImpl command;
30 |
31 | private void createCart(String id) {
32 | Cart cart = Cart.builder()
33 | .id(id)
34 | .build();
35 |
36 | cartRepository.save(cart).block();
37 | }
38 |
39 | @Test
40 | public void testSuccessGetCartDetail() throws Exception {
41 | String cartId = "cart-id";
42 | createCart(cartId);
43 |
44 | GetCartDetailRequest request = GetCartDetailRequest.builder()
45 | .cartId(cartId)
46 | .build();
47 |
48 | Cart result = command.execute(request).block();
49 | assertEquals(cartId, result.getId());
50 | }
51 |
52 | @Test
53 | public void testFailedGetCartDetail() throws Exception {
54 | String cartId = "not-exists";
55 | GetCartDetailRequest request = GetCartDetailRequest.builder()
56 | .cartId(cartId)
57 | .build();
58 |
59 | try {
60 | command.execute(request).block();
61 | fail("It should throw exception");
62 | } catch (CommandValidationException ex) {
63 | ex.getConstraintViolations().forEach(constraintViolation ->
64 | assertEquals("CartMustExists", constraintViolation.getMessage())
65 | );
66 | }
67 | }
68 | }
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/service/command/impl/PingCommandImplTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.model.service.PingRequest;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.test.annotation.DirtiesContext;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * @author Eko Kurniawan Khannedy
15 | * @since 30/06/17
16 | */
17 | @RunWith(SpringRunner.class)
18 | @SpringBootTest
19 | @DirtiesContext
20 | public class PingCommandImplTest {
21 |
22 | @Autowired
23 | private PingCommandImpl pingCommand;
24 |
25 | @Test
26 | public void execute() throws Exception {
27 | String response = pingCommand.execute(PingRequest.builder().build()).block();
28 | assertEquals("Pong", response);
29 | }
30 |
31 | }
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/service/command/impl/RemoveProductFromCartCommandImplTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.CartItem;
5 | import com.idspring.commandpattern.entity.Product;
6 | import com.idspring.commandpattern.model.service.RemoveProductFromCartRequest;
7 | import com.idspring.commandpattern.repository.CartRepository;
8 | import com.idspring.commandpattern.repository.ProductRepository;
9 | import com.idspring.commandpattern.service.exception.CommandValidationException;
10 | import org.junit.Test;
11 | import org.junit.runner.RunWith;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.boot.test.context.SpringBootTest;
14 | import org.springframework.test.annotation.DirtiesContext;
15 | import org.springframework.test.context.junit4.SpringRunner;
16 |
17 | import javax.validation.ConstraintViolation;
18 | import java.util.Collections;
19 | import java.util.List;
20 | import java.util.UUID;
21 | import java.util.stream.Collectors;
22 |
23 | import static org.junit.Assert.*;
24 | import static org.hamcrest.Matchers.*;
25 |
26 | /**
27 | * @author Eko Kurniawan Khannedy
28 | * @since 02/07/17
29 | */
30 | @RunWith(SpringRunner.class)
31 | @SpringBootTest
32 | @DirtiesContext
33 | public class RemoveProductFromCartCommandImplTest {
34 |
35 | @Autowired
36 | private CartRepository cartRepository;
37 |
38 | @Autowired
39 | private ProductRepository productRepository;
40 |
41 | @Autowired
42 | private RemoveProductFromCartCommandImpl command;
43 |
44 | private Cart createCart(String cartId) {
45 | Cart cart = Cart.builder()
46 | .id(cartId)
47 | .build();
48 |
49 | return cartRepository.save(cart).block();
50 | }
51 |
52 | private Cart createCartWithItem(String cartId, String productId) {
53 | Cart cart = Cart.builder()
54 | .id(cartId)
55 | .items(Collections.singletonList(
56 | CartItem.builder()
57 | .id(productId)
58 | .name("Item Name")
59 | .price(1000L)
60 | .quantity(1)
61 | .build()
62 | ))
63 | .build();
64 |
65 | return cartRepository.save(cart).block();
66 | }
67 |
68 | private Product createProduct(String productId) {
69 | Product product = Product.builder()
70 | .id(productId)
71 | .price(1000L)
72 | .stock(10)
73 | .name("Item Name")
74 | .build();
75 |
76 | return productRepository.save(product).block();
77 | }
78 |
79 | @Test
80 | public void testCartNotExists() throws Exception {
81 | String cartId = UUID.randomUUID().toString();
82 | String productId = UUID.randomUUID().toString();
83 |
84 | RemoveProductFromCartRequest request = RemoveProductFromCartRequest.builder()
85 | .cartId(cartId)
86 | .productId(productId)
87 | .build();
88 |
89 | try {
90 | command.execute(request).block();
91 | fail("it should thrown exception");
92 | } catch (CommandValidationException ex) {
93 | List messages = ex.getConstraintViolations().stream()
94 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
95 | assertThat(messages, hasItems("CartMustExists", "ProductMustExists"));
96 | }
97 | }
98 |
99 | @Test
100 | public void testProductNotExists() throws Exception {
101 | String cartId = UUID.randomUUID().toString();
102 | String productId = UUID.randomUUID().toString();
103 |
104 | createCart(cartId);
105 |
106 | RemoveProductFromCartRequest request = RemoveProductFromCartRequest.builder()
107 | .cartId(cartId)
108 | .productId(productId)
109 | .build();
110 |
111 | try {
112 | command.execute(request).block();
113 | fail("it should thrown exception");
114 | } catch (CommandValidationException ex) {
115 | List messages = ex.getConstraintViolations().stream()
116 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
117 | assertThat(messages, hasItems("ProductMustExists"));
118 | }
119 | }
120 |
121 | @Test
122 | public void testProductNotExistsInCart() throws Exception {
123 | String cartId = UUID.randomUUID().toString();
124 | String productId = UUID.randomUUID().toString();
125 |
126 | createCart(cartId);
127 | createProduct(productId);
128 |
129 | RemoveProductFromCartRequest request = RemoveProductFromCartRequest.builder()
130 | .cartId(cartId)
131 | .productId(productId)
132 | .build();
133 |
134 | try {
135 | command.execute(request).block();
136 | fail("it should thrown exception");
137 | } catch (CommandValidationException ex) {
138 | List messages = ex.getConstraintViolations().stream()
139 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
140 | assertThat(messages, hasItems("ProductMustExistsInCart"));
141 | }
142 | }
143 |
144 | @Test
145 | public void testSuccess() throws Exception {
146 | String cartId = UUID.randomUUID().toString();
147 | String productId = UUID.randomUUID().toString();
148 |
149 | createProduct(productId);
150 | createCartWithItem(cartId, productId);
151 |
152 | RemoveProductFromCartRequest request = RemoveProductFromCartRequest.builder()
153 | .cartId(cartId)
154 | .productId(productId)
155 | .build();
156 |
157 | Cart result = command.execute(request).block();
158 | List itemIds = result.getItems().stream()
159 | .map(CartItem::getId).collect(Collectors.toList());
160 |
161 | assertThat(itemIds, not(hasItem(productId)));
162 | }
163 | }
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/service/command/impl/UpdateProductInCartCommandImplTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.command.impl;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.CartItem;
5 | import com.idspring.commandpattern.entity.Product;
6 | import com.idspring.commandpattern.model.service.UpdateProductInCartRequest;
7 | import com.idspring.commandpattern.repository.CartRepository;
8 | import com.idspring.commandpattern.repository.ProductRepository;
9 | import com.idspring.commandpattern.service.command.UpdateProductInCartCommand;
10 | import com.idspring.commandpattern.service.exception.CommandValidationException;
11 | import org.junit.Test;
12 | import org.junit.runner.RunWith;
13 | import org.springframework.beans.factory.annotation.Autowired;
14 | import org.springframework.boot.test.context.SpringBootTest;
15 | import org.springframework.test.annotation.DirtiesContext;
16 | import org.springframework.test.context.junit4.SpringRunner;
17 |
18 | import javax.validation.ConstraintViolation;
19 | import java.util.Collections;
20 | import java.util.List;
21 | import java.util.UUID;
22 | import java.util.stream.Collectors;
23 |
24 | import static org.junit.Assert.*;
25 | import static org.hamcrest.Matchers.*;
26 |
27 | /**
28 | * @author Eko Kurniawan Khannedy
29 | * @since 02/07/17
30 | */
31 | @RunWith(SpringRunner.class)
32 | @SpringBootTest
33 | @DirtiesContext
34 | public class UpdateProductInCartCommandImplTest {
35 |
36 | @Autowired
37 | private CartRepository cartRepository;
38 |
39 | @Autowired
40 | private ProductRepository productRepository;
41 |
42 | @Autowired
43 | private UpdateProductInCartCommandImpl command;
44 |
45 | private Cart createCart(String cartId) {
46 | Cart cart = Cart.builder()
47 | .id(cartId)
48 | .build();
49 |
50 | return cartRepository.save(cart).block();
51 | }
52 |
53 | private Cart createCartWithItem(String cartId, String productId) {
54 | Cart cart = Cart.builder()
55 | .id(cartId)
56 | .items(Collections.singletonList(
57 | CartItem.builder()
58 | .id(productId)
59 | .name("Item Name")
60 | .price(1000L)
61 | .quantity(1)
62 | .build()
63 | ))
64 | .build();
65 |
66 | return cartRepository.save(cart).block();
67 | }
68 |
69 | private Product createProduct(String productId) {
70 | Product product = Product.builder()
71 | .id(productId)
72 | .price(1000L)
73 | .stock(10)
74 | .name("Item Name")
75 | .build();
76 |
77 | return productRepository.save(product).block();
78 | }
79 |
80 | @Test
81 | public void testCartNotExists() throws Exception {
82 | String cartId = UUID.randomUUID().toString();
83 | String productId = UUID.randomUUID().toString();
84 |
85 | UpdateProductInCartRequest request = UpdateProductInCartRequest.builder()
86 | .cartId(cartId)
87 | .productId(productId)
88 | .quantity(1)
89 | .build();
90 |
91 | try {
92 | command.execute(request).block();
93 | fail("It should throw exception");
94 | } catch (CommandValidationException ex) {
95 | List messages = ex.getConstraintViolations().stream()
96 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
97 | assertThat(messages, hasItems("CartMustExists", "ProductMustExists"));
98 | }
99 | }
100 |
101 | @Test
102 | public void testProductNotExists() throws Exception {
103 | String cartId = UUID.randomUUID().toString();
104 | createCart(cartId);
105 |
106 | String productId = UUID.randomUUID().toString();
107 |
108 | UpdateProductInCartRequest request = UpdateProductInCartRequest.builder()
109 | .cartId(cartId)
110 | .productId(productId)
111 | .quantity(1)
112 | .build();
113 |
114 | try {
115 | command.execute(request).block();
116 | fail("It should throw exception");
117 | } catch (CommandValidationException ex) {
118 | List messages = ex.getConstraintViolations().stream()
119 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
120 | assertThat(messages, hasItems("ProductMustExists"));
121 | }
122 | }
123 |
124 | @Test
125 | public void testProductNotExistsInCart() throws Exception {
126 | String cartId = UUID.randomUUID().toString();
127 | createCart(cartId);
128 | String productId = UUID.randomUUID().toString();
129 | createProduct(productId);
130 |
131 | UpdateProductInCartRequest request = UpdateProductInCartRequest.builder()
132 | .cartId(cartId)
133 | .productId(productId)
134 | .quantity(1)
135 | .build();
136 |
137 | try {
138 | command.execute(request).block();
139 | fail("It should throw exception");
140 | } catch (CommandValidationException ex) {
141 | List messages = ex.getConstraintViolations().stream()
142 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
143 | assertThat(messages, hasItems("ProductMustExistsInCart"));
144 | }
145 | }
146 |
147 | @Test
148 | public void testProductQuantityNotEnough() throws Exception {
149 | String productId = UUID.randomUUID().toString();
150 | createProduct(productId);
151 |
152 | String cartId = UUID.randomUUID().toString();
153 | createCartWithItem(cartId, productId);
154 |
155 | UpdateProductInCartRequest request = UpdateProductInCartRequest.builder()
156 | .cartId(cartId)
157 | .productId(productId)
158 | .quantity(10)
159 | .build();
160 |
161 | try {
162 | command.execute(request).block();
163 | fail("It should throw exception");
164 | } catch (CommandValidationException ex) {
165 | List messages = ex.getConstraintViolations().stream()
166 | .map(ConstraintViolation::getMessage).collect(Collectors.toList());
167 | assertThat(messages, hasItems("ProductQuantityMustEnough"));
168 | }
169 | }
170 |
171 | @Test
172 | public void testSuccess() throws Exception {
173 | String productId = UUID.randomUUID().toString();
174 | createProduct(productId);
175 |
176 | String cartId = UUID.randomUUID().toString();
177 | createCartWithItem(cartId, productId);
178 |
179 | UpdateProductInCartRequest request = UpdateProductInCartRequest.builder()
180 | .cartId(cartId)
181 | .productId(productId)
182 | .quantity(5)
183 | .build();
184 |
185 | Cart result = command.execute(request).block();
186 |
187 | assertEquals(Integer.valueOf(6), result.getItems().get(0).getQuantity());
188 | }
189 | }
--------------------------------------------------------------------------------
/spring-command-pattern-service/src/test/java/com/idspring/commandpattern/service/impl/ServiceExecutorImplTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.service.impl;
2 |
3 | import com.idspring.commandpattern.model.service.ServiceRequest;
4 | import com.idspring.commandpattern.service.Command;
5 | import com.idspring.commandpattern.service.command.PingCommand;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 | import org.springframework.beans.BeansException;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.test.annotation.DirtiesContext;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 | import reactor.core.publisher.Mono;
14 |
15 | import static org.junit.Assert.*;
16 | import static org.mockito.Mockito.*;
17 |
18 | /**
19 | * @author Eko Kurniawan Khannedy
20 | * @since 30/06/17
21 | */
22 | @RunWith(SpringRunner.class)
23 | @SpringBootTest
24 | @DirtiesContext
25 | public class ServiceExecutorImplTest {
26 |
27 | @Autowired
28 | private ServiceExecutorImpl serviceExecutor;
29 |
30 | @Test
31 | public void testExecutePingCommand() throws Exception {
32 | ServiceRequest request = mock(ServiceRequest.class);
33 | String result = serviceExecutor.execute(PingCommand.class, request).block();
34 |
35 | assertEquals("Pong", result);
36 | }
37 |
38 | @Test(expected = BeansException.class)
39 | public void testCommandNotFound() throws Exception {
40 | ServiceRequest request = mock(ServiceRequest.class);
41 | serviceExecutor.execute(UnknownCommand.class, request);
42 |
43 | fail("It should be throw BeansException");
44 | }
45 |
46 | static class UnknownCommand implements Command {
47 |
48 | @Override
49 | public Mono execute(ServiceRequest request) {
50 | return Mono.empty();
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/spring-command-pattern-validation/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | command-pattern
7 | com.idspring
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | spring-command-pattern-validation
13 |
14 |
15 |
16 | com.idspring
17 | spring-command-pattern-repository
18 | ${project.parent.version}
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/CartMustExists.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation;
2 |
3 | import com.idspring.commandpattern.validation.validator.CartMustExistsValidator;
4 |
5 | import javax.validation.Constraint;
6 | import javax.validation.Payload;
7 | import java.lang.annotation.Documented;
8 | import java.lang.annotation.Retention;
9 | import java.lang.annotation.Target;
10 |
11 | import static java.lang.annotation.ElementType.*;
12 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
13 |
14 | /**
15 | * @author Eko Kurniawan Khannedy
16 | * @since 30/06/17
17 | */
18 | @Target({TYPE, ANNOTATION_TYPE, METHOD, FIELD})
19 | @Retention(RUNTIME)
20 | @Constraint(validatedBy = {CartMustExistsValidator.class})
21 | @Documented
22 | public @interface CartMustExists {
23 |
24 | String message() default "CartMustExists";
25 |
26 | Class>[] groups() default {};
27 |
28 | Class extends Payload>[] payload() default {};
29 |
30 | String[] path() default {};
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/CartMustNotExists.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation;
2 |
3 | import com.idspring.commandpattern.validation.validator.CartMustNotExistsValidator;
4 |
5 | import javax.validation.Constraint;
6 | import javax.validation.Payload;
7 | import java.lang.annotation.Documented;
8 | import java.lang.annotation.Retention;
9 | import java.lang.annotation.Target;
10 |
11 | import static java.lang.annotation.ElementType.*;
12 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
13 |
14 | /**
15 | * @author Eko Kurniawan Khannedy
16 | * @since 30/06/17
17 | */
18 | @Target({TYPE, ANNOTATION_TYPE, METHOD, FIELD})
19 | @Retention(RUNTIME)
20 | @Constraint(validatedBy = {CartMustNotExistsValidator.class})
21 | @Documented
22 | public @interface CartMustNotExists {
23 |
24 | String message() default "CartMustNotExists";
25 |
26 | Class>[] groups() default {};
27 |
28 | Class extends Payload>[] payload() default {};
29 |
30 | String[] path() default {};
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/ProductMustExists.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation;
2 |
3 | import com.idspring.commandpattern.validation.validator.ProductMustExistsValidator;
4 |
5 | import javax.validation.Constraint;
6 | import javax.validation.Payload;
7 |
8 | import java.lang.annotation.Documented;
9 | import java.lang.annotation.Retention;
10 | import java.lang.annotation.Target;
11 |
12 | import static java.lang.annotation.ElementType.*;
13 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
14 |
15 | /**
16 | * @author Eko Kurniawan Khannedy
17 | * @since 30/06/17
18 | */
19 | @Target({TYPE, ANNOTATION_TYPE, METHOD, FIELD})
20 | @Retention(RUNTIME)
21 | @Constraint(validatedBy = {ProductMustExistsValidator.class})
22 | @Documented
23 | public @interface ProductMustExists {
24 |
25 | String message() default "ProductMustExists";
26 |
27 | Class>[] groups() default {};
28 |
29 | Class extends Payload>[] payload() default {};
30 |
31 | String[] path() default {};
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/ProductMustExistsInCart.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation;
2 |
3 | import com.idspring.commandpattern.validation.validator.ProductMustExistsInCartValidator;
4 |
5 | import javax.validation.Constraint;
6 | import javax.validation.Payload;
7 | import java.lang.annotation.Documented;
8 | import java.lang.annotation.Retention;
9 | import java.lang.annotation.Target;
10 |
11 | import static java.lang.annotation.ElementType.*;
12 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
13 |
14 | /**
15 | * @author Eko Kurniawan Khannedy
16 | * @since 01/07/17
17 | */
18 | @Target({TYPE, ANNOTATION_TYPE, METHOD, FIELD})
19 | @Retention(RUNTIME)
20 | @Constraint(validatedBy = {ProductMustExistsInCartValidator.class})
21 | @Documented
22 | public @interface ProductMustExistsInCart {
23 |
24 | String message() default "ProductMustExistsInCart";
25 |
26 | Class>[] groups() default {};
27 |
28 | Class extends Payload>[] payload() default {};
29 |
30 | String[] path() default {};
31 |
32 | interface ProductInCart {
33 |
34 | String getCartId();
35 |
36 | String getProductId();
37 |
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/ProductQuantityMustEnough.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation;
2 |
3 | import com.idspring.commandpattern.validation.validator.ProductQuantityMustEnoughValidator;
4 | import com.idspring.commandpattern.validation.validator.ProductQuantityUpdateMustEnoughValidator;
5 |
6 | import javax.validation.Constraint;
7 | import javax.validation.Payload;
8 | import java.lang.annotation.Documented;
9 | import java.lang.annotation.Retention;
10 | import java.lang.annotation.Target;
11 |
12 | import static java.lang.annotation.ElementType.*;
13 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
14 |
15 | /**
16 | * @author Eko Kurniawan Khannedy
17 | * @since 30/06/17
18 | */
19 | @Target({TYPE, ANNOTATION_TYPE, METHOD, FIELD})
20 | @Retention(RUNTIME)
21 | @Constraint(validatedBy = {
22 | ProductQuantityMustEnoughValidator.class,
23 | ProductQuantityUpdateMustEnoughValidator.class
24 | })
25 | @Documented
26 | public @interface ProductQuantityMustEnough {
27 |
28 | String message() default "ProductQuantityMustEnough";
29 |
30 | Class>[] groups() default {};
31 |
32 | Class extends Payload>[] payload() default {};
33 |
34 | String[] path() default {};
35 |
36 | interface ProductQuantity {
37 |
38 | String getProductId();
39 |
40 | Integer getQuantity();
41 |
42 | }
43 |
44 | interface ProductQuantityUpdate {
45 |
46 | String getCartId();
47 |
48 | String getProductId();
49 |
50 | Integer getQuantity();
51 |
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Eko Kurniawan Khannedy
3 | * @since 30/06/17
4 | */
5 | package com.idspring.commandpattern.validation;
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/validator/CartMustExistsValidator.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.repository.CartRepository;
4 | import com.idspring.commandpattern.validation.CartMustExists;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Component;
7 |
8 | import javax.validation.ConstraintValidator;
9 | import javax.validation.ConstraintValidatorContext;
10 |
11 | /**
12 | * @author Eko Kurniawan Khannedy
13 | * @since 30/06/17
14 | */
15 | @Component
16 | public class CartMustExistsValidator implements ConstraintValidator {
17 |
18 | @Autowired
19 | private CartRepository cartRepository;
20 |
21 | @Override
22 | public void initialize(CartMustExists constraintAnnotation) {
23 |
24 | }
25 |
26 | @Override
27 | public boolean isValid(String value, ConstraintValidatorContext context) {
28 | if (value == null) {
29 | return true;
30 | }
31 |
32 | return cartRepository.existsById(value).block();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/validator/CartMustNotExistsValidator.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.repository.CartRepository;
4 | import com.idspring.commandpattern.validation.CartMustNotExists;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Component;
7 |
8 | import javax.validation.ConstraintValidator;
9 | import javax.validation.ConstraintValidatorContext;
10 |
11 | /**
12 | * @author Eko Kurniawan Khannedy
13 | * @since 30/06/17
14 | */
15 | @Component
16 | public class CartMustNotExistsValidator implements ConstraintValidator {
17 |
18 | @Autowired
19 | private CartRepository cartRepository;
20 |
21 | @Override
22 | public void initialize(CartMustNotExists constraintAnnotation) {
23 |
24 | }
25 |
26 | @Override
27 | public boolean isValid(String value, ConstraintValidatorContext context) {
28 | if (value == null) {
29 | return true;
30 | }
31 |
32 | return cartRepository.existsById(value).block() == Boolean.FALSE;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/validator/ProductMustExistsInCartValidator.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.Product;
5 | import com.idspring.commandpattern.repository.CartRepository;
6 | import com.idspring.commandpattern.repository.ProductRepository;
7 | import com.idspring.commandpattern.validation.ProductMustExists;
8 | import com.idspring.commandpattern.validation.ProductMustExistsInCart;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.stereotype.Component;
11 |
12 | import javax.validation.ConstraintValidator;
13 | import javax.validation.ConstraintValidatorContext;
14 |
15 | /**
16 | * @author Eko Kurniawan Khannedy
17 | * @since 30/06/17
18 | */
19 | @Component
20 | public class ProductMustExistsInCartValidator implements ConstraintValidator {
21 |
22 | @Autowired
23 | private CartRepository cartRepository;
24 |
25 | @Override
26 | public void initialize(ProductMustExistsInCart constraintAnnotation) {
27 |
28 | }
29 |
30 | @Override
31 | public boolean isValid(ProductMustExistsInCart.ProductInCart value, ConstraintValidatorContext context) {
32 | if (value == null) {
33 | return true;
34 | }
35 |
36 | Cart cart = cartRepository.findById(value.getCartId()).block();
37 | if (cart == null) {
38 | return true;
39 | }
40 |
41 | if (cart.getItems() == null || cart.getItems().isEmpty()) {
42 | return false;
43 | }
44 |
45 | return cart.getItems().stream()
46 | .anyMatch(cartItem -> cartItem.getId().equals(value.getProductId()));
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/validator/ProductMustExistsValidator.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Product;
4 | import com.idspring.commandpattern.repository.ProductRepository;
5 | import com.idspring.commandpattern.validation.ProductMustExists;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Component;
8 |
9 | import javax.validation.ConstraintValidator;
10 | import javax.validation.ConstraintValidatorContext;
11 |
12 | /**
13 | * @author Eko Kurniawan Khannedy
14 | * @since 30/06/17
15 | */
16 | @Component
17 | public class ProductMustExistsValidator implements ConstraintValidator {
18 |
19 | @Autowired
20 | private ProductRepository productRepository;
21 |
22 | @Override
23 | public void initialize(ProductMustExists constraintAnnotation) {
24 |
25 | }
26 |
27 | @Override
28 | public boolean isValid(String value, ConstraintValidatorContext context) {
29 | if (value == null) {
30 | return true;
31 | }
32 |
33 | Product product = productRepository.findById(value).block();
34 | return product != null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/validator/ProductQuantityMustEnoughValidator.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Product;
4 | import com.idspring.commandpattern.repository.ProductRepository;
5 | import com.idspring.commandpattern.validation.ProductQuantityMustEnough;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Component;
8 |
9 | import javax.validation.ConstraintValidator;
10 | import javax.validation.ConstraintValidatorContext;
11 |
12 | /**
13 | * @author Eko Kurniawan Khannedy
14 | * @since 30/06/17
15 | */
16 | @Component
17 | public class ProductQuantityMustEnoughValidator implements
18 | ConstraintValidator {
19 |
20 | @Autowired
21 | private ProductRepository productRepository;
22 |
23 | @Override
24 | public void initialize(ProductQuantityMustEnough constraintAnnotation) {
25 |
26 | }
27 |
28 | @Override
29 | public boolean isValid(ProductQuantityMustEnough.ProductQuantity value, ConstraintValidatorContext context) {
30 | if (value == null || value.getProductId() == null || value.getQuantity() == null) {
31 | return true;
32 | }
33 |
34 | Product product = productRepository.findById(value.getProductId()).block();
35 |
36 | if (isProductNotExists(product)) {
37 | return true;
38 | }
39 |
40 | return isStockEnough(product, value.getQuantity());
41 | }
42 |
43 | private boolean isProductNotExists(Product product) {
44 | return product == null;
45 | }
46 |
47 | private boolean isStockEnough(Product product, Integer quantity) {
48 | return product.getStock() >= quantity;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/main/java/com/idspring/commandpattern/validation/validator/ProductQuantityUpdateMustEnoughValidator.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.entity.CartItem;
5 | import com.idspring.commandpattern.entity.Product;
6 | import com.idspring.commandpattern.repository.CartRepository;
7 | import com.idspring.commandpattern.repository.ProductRepository;
8 | import com.idspring.commandpattern.validation.ProductQuantityMustEnough;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.stereotype.Component;
11 |
12 | import javax.validation.ConstraintValidator;
13 | import javax.validation.ConstraintValidatorContext;
14 | import java.util.Optional;
15 |
16 | /**
17 | * @author Eko Kurniawan Khannedy
18 | * @since 30/06/17
19 | */
20 | @Component
21 | public class ProductQuantityUpdateMustEnoughValidator implements
22 | ConstraintValidator {
23 |
24 | @Autowired
25 | private ProductRepository productRepository;
26 |
27 | @Autowired
28 | private CartRepository cartRepository;
29 |
30 | @Override
31 | public void initialize(ProductQuantityMustEnough constraintAnnotation) {
32 |
33 | }
34 |
35 | @Override
36 | public boolean isValid(ProductQuantityMustEnough.ProductQuantityUpdate value, ConstraintValidatorContext context) {
37 | if (value == null || value.getProductId() == null || value.getQuantity() == null) {
38 | return true;
39 | }
40 |
41 | Cart cart = cartRepository.findById(value.getCartId()).block();
42 |
43 | if (cart == null || cart.getItems() == null || cart.getItems().isEmpty()) {
44 | return true;
45 | }
46 |
47 | Optional cartItemOptional = getCartItemByProductId(cart, value.getProductId());
48 |
49 | if (!cartItemOptional.isPresent()) {
50 | return true;
51 | }
52 |
53 | Product product = productRepository.findById(value.getProductId()).block();
54 |
55 | if (product == null) {
56 | return false;
57 | }
58 |
59 | if (product.getStock() < value.getQuantity()) {
60 | return false;
61 | }
62 |
63 | return product.getStock() >= (cartItemOptional.get().getQuantity() + value.getQuantity());
64 | }
65 |
66 | private Optional getCartItemByProductId(Cart cart, String productId) {
67 | return cart.getItems().stream()
68 | .filter(cartItem -> cartItem.getId().equals(productId))
69 | .findFirst();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/test/java/com/idspring/commandpattern/SpringCommandPatternApplication.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern;
2 |
3 | import org.springframework.boot.autoconfigure.SpringBootApplication;
4 |
5 | @SpringBootApplication
6 | public class SpringCommandPatternApplication {
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/test/java/com/idspring/commandpattern/validation/validator/CartMustExistsValidatorTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.repository.CartRepository;
5 | import com.idspring.commandpattern.validation.CartMustExists;
6 | import lombok.Builder;
7 | import lombok.Data;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.context.SpringBootTest;
12 | import org.springframework.test.annotation.DirtiesContext;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import javax.validation.ConstraintViolation;
16 | import javax.validation.Validator;
17 |
18 | import java.util.Collections;
19 | import java.util.Set;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | /**
24 | * @author Eko Kurniawan Khannedy
25 | * @since 01/07/17
26 | */
27 | @RunWith(SpringRunner.class)
28 | @SpringBootTest
29 | @DirtiesContext
30 | public class CartMustExistsValidatorTest {
31 |
32 | @Autowired
33 | private CartRepository cartRepository;
34 |
35 | @Autowired
36 | private Validator validator;
37 |
38 | private void createCart(String id) {
39 | Cart cart = Cart.builder()
40 | .id(id)
41 | .items(Collections.emptyList())
42 | .build();
43 |
44 | cartRepository.save(cart).block();
45 | }
46 |
47 | @Test
48 | public void testValid() throws Exception {
49 | String cartId = "sample-cart-id";
50 | createCart(cartId);
51 |
52 | FooData data = FooData.builder()
53 | .cartId(cartId)
54 | .build();
55 |
56 | Set> constraintViolations = validator.validate(data);
57 | assertEquals(0, constraintViolations.size());
58 | }
59 |
60 | @Test
61 | public void testNullMustValid() throws Exception {
62 | FooData data = FooData.builder()
63 | .cartId(null)
64 | .build();
65 |
66 | Set> constraintViolations = validator.validate(data);
67 | assertEquals(0, constraintViolations.size());
68 | }
69 |
70 | @Test
71 | public void testInvalid() throws Exception {
72 | String cartId = "non-exists";
73 | FooData data = FooData.builder()
74 | .cartId(cartId)
75 | .build();
76 |
77 | Set> constraintViolations = validator.validate(data);
78 | assertEquals(1, constraintViolations.size());
79 |
80 | constraintViolations.forEach(fooDataConstraintViolation -> {
81 | assertEquals("CartMustExists", fooDataConstraintViolation.getMessage());
82 | });
83 | }
84 |
85 | @Data
86 | @Builder
87 | static class FooData {
88 |
89 | @CartMustExists
90 | private String cartId;
91 | }
92 | }
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/test/java/com/idspring/commandpattern/validation/validator/CartMustNotExistsValidatorTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.repository.CartRepository;
5 | import com.idspring.commandpattern.validation.CartMustNotExists;
6 | import lombok.Builder;
7 | import lombok.Data;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.context.SpringBootTest;
12 | import org.springframework.test.annotation.DirtiesContext;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import javax.validation.ConstraintViolation;
16 | import javax.validation.Validator;
17 | import java.util.Collections;
18 | import java.util.Set;
19 |
20 | import static org.junit.Assert.*;
21 |
22 | /**
23 | * @author Eko Kurniawan Khannedy
24 | * @since 01/07/17
25 | */
26 | @RunWith(SpringRunner.class)
27 | @SpringBootTest
28 | @DirtiesContext
29 | public class CartMustNotExistsValidatorTest {
30 |
31 | @Autowired
32 | private CartRepository cartRepository;
33 |
34 | @Autowired
35 | private Validator validator;
36 |
37 | private void createCart(String id) {
38 | Cart cart = Cart.builder()
39 | .id(id)
40 | .items(Collections.emptyList())
41 | .build();
42 |
43 | cartRepository.save(cart).block();
44 | }
45 |
46 | @Test
47 | public void testValid() throws Exception {
48 | String cartId = "not-exists";
49 | FooData data = FooData.builder()
50 | .cartId(cartId)
51 | .build();
52 |
53 | Set> constraintViolations = validator.validate(data);
54 | assertEquals(0, constraintViolations.size());
55 | }
56 |
57 | @Test
58 | public void testNullMustValid() throws Exception {
59 | FooData data = FooData.builder()
60 | .cartId(null)
61 | .build();
62 |
63 | Set> constraintViolations = validator.validate(data);
64 | assertEquals(0, constraintViolations.size());
65 | }
66 |
67 | @Test
68 | public void testInvalid() throws Exception {
69 | String cartId = "exists";
70 | createCart(cartId);
71 | FooData data = FooData.builder()
72 | .cartId(cartId)
73 | .build();
74 |
75 | Set> constraintViolations = validator.validate(data);
76 | assertEquals(1, constraintViolations.size());
77 |
78 | constraintViolations.forEach(fooDataConstraintViolation -> {
79 | assertEquals("CartMustNotExists", fooDataConstraintViolation.getMessage());
80 | });
81 | }
82 |
83 | @Data
84 | @Builder
85 | static class FooData {
86 |
87 | @CartMustNotExists
88 | private String cartId;
89 | }
90 | }
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/test/java/com/idspring/commandpattern/validation/validator/ProductMustExistsValidatorTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Product;
4 | import com.idspring.commandpattern.repository.ProductRepository;
5 | import com.idspring.commandpattern.validation.ProductMustExists;
6 | import lombok.Builder;
7 | import lombok.Data;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.context.SpringBootTest;
12 | import org.springframework.test.annotation.DirtiesContext;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import javax.validation.ConstraintViolation;
16 | import javax.validation.Validator;
17 |
18 | import java.util.Set;
19 |
20 | import static org.junit.Assert.*;
21 |
22 | /**
23 | * @author Eko Kurniawan Khannedy
24 | * @since 01/07/17
25 | */
26 | @RunWith(SpringRunner.class)
27 | @SpringBootTest
28 | @DirtiesContext
29 | public class ProductMustExistsValidatorTest {
30 |
31 | @Autowired
32 | private ProductRepository productRepository;
33 |
34 | @Autowired
35 | private Validator validator;
36 |
37 | private void createProduct(String id) {
38 | Product product = Product.builder()
39 | .id(id)
40 | .name("Name")
41 | .stock(1000)
42 | .price(1000L)
43 | .build();
44 |
45 | productRepository.save(product).block();
46 | }
47 |
48 | @Test
49 | public void testValid() throws Exception {
50 | String productId = "sample-product-id";
51 | createProduct(productId);
52 |
53 | FooData data = FooData.builder()
54 | .productId(productId)
55 | .build();
56 |
57 | Set> constraintViolations = validator.validate(data);
58 | assertEquals(0, constraintViolations.size());
59 | }
60 |
61 | @Test
62 | public void testNullMustValid() throws Exception {
63 | FooData data = FooData.builder()
64 | .productId(null)
65 | .build();
66 |
67 | Set> constraintViolations = validator.validate(data);
68 | assertEquals(0, constraintViolations.size());
69 | }
70 |
71 | @Test
72 | public void testInvalid() throws Exception {
73 | String productId = "not-exists";
74 | FooData data = FooData.builder()
75 | .productId(productId)
76 | .build();
77 |
78 | Set> constraintViolations = validator.validate(data);
79 | assertEquals(1, constraintViolations.size());
80 |
81 | constraintViolations.forEach(fooDataConstraintViolation -> {
82 | assertEquals("ProductMustExists", fooDataConstraintViolation.getMessage());
83 | });
84 | }
85 |
86 | @Data
87 | @Builder
88 | static class FooData {
89 |
90 | @ProductMustExists
91 | private String productId;
92 |
93 | }
94 | }
--------------------------------------------------------------------------------
/spring-command-pattern-validation/src/test/java/com/idspring/commandpattern/validation/validator/ProductQuantityMustEnoughValidatorTest.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.validation.validator;
2 |
3 | import com.idspring.commandpattern.entity.Product;
4 | import com.idspring.commandpattern.repository.ProductRepository;
5 | import com.idspring.commandpattern.validation.ProductQuantityMustEnough;
6 | import lombok.Builder;
7 | import lombok.Data;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.context.SpringBootTest;
12 | import org.springframework.test.annotation.DirtiesContext;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import javax.validation.ConstraintViolation;
16 | import javax.validation.Validator;
17 |
18 | import java.util.Set;
19 |
20 | import static org.junit.Assert.*;
21 |
22 | /**
23 | * @author Eko Kurniawan Khannedy
24 | * @since 01/07/17
25 | */
26 | @RunWith(SpringRunner.class)
27 | @SpringBootTest
28 | @DirtiesContext
29 | public class ProductQuantityMustEnoughValidatorTest {
30 |
31 | @Autowired
32 | private ProductRepository productRepository;
33 |
34 | @Autowired
35 | private Validator validator;
36 |
37 | private void createProduct(String id, Integer stock) {
38 | Product product = Product.builder()
39 | .id(id)
40 | .name("Name")
41 | .stock(stock)
42 | .price(1000L)
43 | .build();
44 |
45 | productRepository.save(product).block();
46 | }
47 |
48 | @Test
49 | public void testValid() throws Exception {
50 | String productId = "sample-product-id";
51 | createProduct(productId, 1000);
52 |
53 | FooData data = FooData.builder()
54 | .productId(productId)
55 | .quantity(10)
56 | .build();
57 |
58 | Set> constraintViolations = validator.validate(data);
59 | assertEquals(0, constraintViolations.size());
60 | }
61 |
62 | @Test
63 | public void testNullMustValid() throws Exception {
64 | FooData data = FooData.builder()
65 | .productId(null)
66 | .build();
67 |
68 | Set> constraintViolations = validator.validate(data);
69 | assertEquals(0, constraintViolations.size());
70 | }
71 |
72 | @Test
73 | public void testInvalid() throws Exception {
74 | String productId = "sample-product-id";
75 | createProduct(productId, 0);
76 |
77 | FooData data = FooData.builder()
78 | .productId(productId)
79 | .quantity(10)
80 | .build();
81 |
82 | Set> constraintViolations = validator.validate(data);
83 | assertEquals(1, constraintViolations.size());
84 |
85 | constraintViolations.forEach(fooDataConstraintViolation -> {
86 | assertEquals("ProductQuantityMustEnough", fooDataConstraintViolation.getMessage());
87 | });
88 | }
89 |
90 | @Builder
91 | @Data
92 | @ProductQuantityMustEnough
93 | static class FooData implements ProductQuantityMustEnough.ProductQuantity {
94 |
95 | private String productId;
96 |
97 | private Integer quantity;
98 |
99 | }
100 | }
--------------------------------------------------------------------------------
/spring-command-pattern-web/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | command-pattern
7 | com.idspring
8 | 0.0.1-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | spring-command-pattern-web
13 |
14 |
15 |
16 | com.idspring
17 | spring-command-pattern-service
18 | ${project.parent.version}
19 |
20 |
21 | com.idspring
22 | spring-command-pattern-properties
23 | ${project.parent.version}
24 |
25 |
26 | com.idspring
27 | spring-command-pattern-model
28 | ${project.parent.version}
29 |
30 |
31 | com.idspring
32 | spring-command-pattern-validation
33 | ${project.parent.version}
34 |
35 |
36 |
37 |
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-maven-plugin
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/spring-command-pattern-web/src/main/java/com/idspring/commandpattern/SpringCommandPatternApplication.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringCommandPatternApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringCommandPatternApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/spring-command-pattern-web/src/main/java/com/idspring/commandpattern/controller/CartController.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.controller;
2 |
3 | import com.idspring.commandpattern.entity.Cart;
4 | import com.idspring.commandpattern.model.controller.CartAddProductRequest;
5 | import com.idspring.commandpattern.model.controller.CartUpdateProductRequest;
6 | import com.idspring.commandpattern.model.controller.Response;
7 | import com.idspring.commandpattern.model.service.*;
8 | import com.idspring.commandpattern.service.ServiceExecutor;
9 | import com.idspring.commandpattern.service.command.*;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.http.MediaType;
12 | import org.springframework.web.bind.annotation.*;
13 | import reactor.core.publisher.Mono;
14 | import reactor.core.scheduler.Schedulers;
15 |
16 | /**
17 | * @author Eko Kurniawan Khannedy
18 | * @since 30/06/17
19 | */
20 | @RestController
21 | @RequestMapping("/carts")
22 | public class CartController {
23 |
24 | @Autowired
25 | private ServiceExecutor serviceExecutor;
26 |
27 | @RequestMapping(value = "/{cartId}", method = RequestMethod.POST,
28 | produces = MediaType.APPLICATION_JSON_VALUE)
29 | public Mono> create(@PathVariable("cartId") String cartId) {
30 | CreateNewCartRequest request = CreateNewCartRequest.builder()
31 | .cartId(cartId)
32 | .build();
33 |
34 | return serviceExecutor.execute(CreateNewCartCommand.class, request)
35 | .map(Response::ok)
36 | .subscribeOn(Schedulers.elastic());
37 | }
38 |
39 | @RequestMapping(value = "/{cartId}/_add-product", method = RequestMethod.POST,
40 | produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
41 | public Mono> addProduct(@PathVariable("cartId") String cartId,
42 | @RequestBody CartAddProductRequest requestBody) {
43 | AddProductToCartRequest request = AddProductToCartRequest.builder()
44 | .cartId(cartId)
45 | .productId(requestBody.getProductId())
46 | .quantity(requestBody.getQuantity())
47 | .build();
48 |
49 | return serviceExecutor.execute(AddProductToCartCommand.class, request)
50 | .map(Response::ok)
51 | .subscribeOn(Schedulers.elastic());
52 | }
53 |
54 | @RequestMapping(value = "/{cartId}", method = RequestMethod.GET,
55 | produces = MediaType.APPLICATION_JSON_VALUE)
56 | public Mono> detail(@PathVariable("cartId") String cartId) {
57 | GetCartDetailRequest request = GetCartDetailRequest.builder()
58 | .cartId(cartId)
59 | .build();
60 |
61 | return serviceExecutor.execute(GetCartDetailCommand.class, request)
62 | .map(Response::ok)
63 | .subscribeOn(Schedulers.elastic());
64 | }
65 |
66 | @RequestMapping(value = "/{cartId}/_update-product", method = RequestMethod.PUT,
67 | produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
68 | public Mono> updateProduct(@PathVariable("cartId") String cartId,
69 | @RequestBody CartUpdateProductRequest requestBody) {
70 | UpdateProductInCartRequest request = UpdateProductInCartRequest.builder()
71 | .cartId(cartId)
72 | .productId(requestBody.getProductId())
73 | .quantity(requestBody.getQuantity())
74 | .build();
75 |
76 | return serviceExecutor.execute(UpdateProductInCartCommand.class, request)
77 | .map(Response::ok)
78 | .subscribeOn(Schedulers.elastic());
79 | }
80 |
81 | @RequestMapping(value = "/{cartId}/{productId}", method = RequestMethod.DELETE,
82 | produces = MediaType.APPLICATION_JSON_VALUE)
83 | public Mono> removeProduct(@PathVariable("cartId") String cartId,
84 | @PathVariable("productId") String productId) {
85 | RemoveProductFromCartRequest request = RemoveProductFromCartRequest.builder()
86 | .cartId(cartId)
87 | .productId(productId)
88 | .build();
89 |
90 | return serviceExecutor.execute(RemoveProductFromCartCommand.class, request)
91 | .map(Response::ok)
92 | .subscribeOn(Schedulers.elastic());
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/spring-command-pattern-web/src/main/java/com/idspring/commandpattern/controller/ExceptionController.java:
--------------------------------------------------------------------------------
1 | package com.idspring.commandpattern.controller;
2 |
3 | import com.idspring.commandpattern.model.controller.Response;
4 | import com.idspring.commandpattern.service.exception.CommandValidationException;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.web.bind.annotation.ExceptionHandler;
7 | import org.springframework.web.bind.annotation.ResponseStatus;
8 | import org.springframework.web.bind.annotation.RestControllerAdvice;
9 |
10 | import javax.validation.ConstraintViolation;
11 | import javax.validation.Path;
12 |
13 | /**
14 | * @author Eko Kurniawan Khannedy
15 | * @since 01/07/17
16 | */
17 | @RestControllerAdvice
18 | public class ExceptionController {
19 |
20 | @ExceptionHandler(Throwable.class)
21 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
22 | public Response