Compare commits

...

46 Commits

Author SHA1 Message Date
thombergs
7cd125ee33 added to build-all.sh 2020-03-11 06:40:03 +11:00
thombergs
76e97842a2 Merge branch 'reflect-91' of https://github.com/Petros0/code-examples into openapi 2020-03-11 06:18:52 +11:00
thombergs
92aef0228e billingmodule -> billing 2020-03-11 05:45:01 +11:00
thombergs
e8ef69917a billingmodule -> billing 2020-03-10 07:05:08 +11:00
thombergs
8a36085425 added missing Gradle files 2020-03-07 08:42:37 +11:00
thombergs
1916f5b2af example for clean architecture boundaries with Spring Boot 2020-03-07 08:26:15 +11:00
thombergs
c69957d1b8 listContributors -> contributors 2020-03-06 06:40:27 +11:00
thombergs
426d1e77c6 Merge remote-tracking branch 'origin/master' 2020-03-05 06:23:17 +11:00
thombergs
ec681b5abc Repository -> GitRepository 2020-03-05 06:23:01 +11:00
Tom Hombergs
57ff03707c Merge pull request #19 from arkuksin/spring-boot-password-emcoding
add project spring-boot/password-encoding
2020-03-04 05:50:59 +11:00
thombergs
761fdd4d7a Merge remote-tracking branch 'origin/master'
# Conflicts:
#	build-all.sh
2020-03-02 21:17:41 +11:00
thombergs
939e864a4a example of converters in Spring Data JDBC 2020-03-02 21:16:33 +11:00
akuksin
84c593016b replace @Autowired by @Bean annotation for the authentication provider 2020-03-01 11:41:50 +01:00
akuksin
e0a456724d remove custom code for password migration, use the feature of DelegatingPasswordEncoder instead 2020-03-01 10:48:52 +01:00
Tom Hombergs
c8a15d4d4d Merge pull request #20 from thombergs/argumentresolver
Argumentresolver
2020-03-01 09:37:07 +11:00
thombergs
34e0bfc156 argumentresolver example 2020-03-01 09:20:29 +11:00
thombergs
dfbc0446c9 MethodArgumentResolver example 2020-02-29 15:18:13 +11:00
akuksin
0b9a101b08 rename JdbcUserDetailPasswordService to DatabaseUserDetailPasswordService 2020-02-28 19:32:50 +01:00
akuksin
1b9f2426a4 remove @Transactional annotation from RegistrationResource 2020-02-27 22:42:36 +01:00
akuksin
3ab8517320 rename UserResources to RegistrationResource 2020-02-27 22:40:11 +01:00
akuksin
77151d1752 rename daoAuthenticationProvider to provider 2020-02-27 22:36:06 +01:00
akuksin
b73731159f rename JdbcUserDetailsService to DatabaseUserDetailsService 2020-02-27 22:22:16 +01:00
akuksin
bfd004b73a make classes package private, apply google-java-formatter 2020-02-27 22:17:40 +01:00
Tom Hombergs
71d2a32f2f Merge pull request #14 from mukul-s/master
Reflect-76 ISP explained added code examples
2020-02-27 06:21:22 +11:00
thombergs
1e4e88c05e small changes to Main 2020-02-27 06:19:59 +11:00
akuksin
ab5143cb2f remove unnecessary comment 2020-02-25 21:58:33 +01:00
Mukul Sharma
5fab70b931 Merge branch 'master' of https://github.com/mukul-s/code-examples 2020-02-26 01:55:03 +05:30
Mukul Sharma
3be25df928 Reflect-76 Added package 2020-02-26 01:54:18 +05:30
akuksin
74f0e28e8e simplify the configuration 2020-02-25 20:12:30 +01:00
Mukul Sharma
f66aa05afb Merge branch 'master' of https://github.com/mukul-s/code-examples 2020-02-25 18:20:32 +05:30
Mukul Sharma
66d275d667 Merge branch 'master' of https://github.com/mukul-s/code-examples 2020-02-25 18:19:31 +05:30
Mukul Sharma
34211bfac9 Reflect 76 - Resolved merge conflicts 2020-02-25 18:18:53 +05:30
Mukul Sharma
1380621113 Resolved merge conflicts 2020-02-25 18:11:04 +05:30
akuksin
d55ee992f3 reformat code 2020-02-22 23:39:48 +01:00
akuksin
9a378b5763 add calculation of bcryt strength with Divide-and-conquer algorithm 2020-02-22 23:35:21 +01:00
akuksin
4ca9b30b94 add simple examples for password encoders 2020-02-20 22:10:17 +01:00
Tom Hombergs
6e0af82475 Merge pull request #13 from petromir/master
Code examples for REFLECT-2 Contributor article
2020-02-21 06:24:57 +11:00
Tom Hombergs
7494ff7f89 Merge branch 'master' into master 2020-02-20 21:38:54 +11:00
thombergs
327e849575 included flyway module in build-all.sh 2020-02-20 21:38:00 +11:00
Petromir Dzhunev
a0ad81a332 REFLECT-2 Add missing bits
Add undo migration, add Jenkins files, add Java-base migration
2020-02-18 17:38:33 +02:00
akuksin
0847972b5a add project spring-boot/password-encoding 2020-02-17 22:24:01 +01:00
thombergs
8ca0e6e380 changes after review 2020-02-02 08:29:36 +11:00
Mukul Sharma
7934eed0ab Reflect-76 ISP explained added code examples 2020-02-01 04:13:37 +05:30
Petromir Dzhunev
1809361301 REFLECT-2 Remove redundant parameters to Gradle plugin 2020-01-29 23:17:09 +02:00
Petromir Dzhunev
01828e504d REFLECT-2 Integrating H2 with Flyway 2020-01-24 22:35:17 +02:00
Petromir Dzhunev
a2bb00faf1 Initial set-up of Flyway data migration project 2020-01-01 19:35:57 +02:00
128 changed files with 3902 additions and 0 deletions

View File

@@ -28,8 +28,40 @@ build_gradle_module() {
}
}
build_maven_module() {
MODULE_PATH=$1
echo ""
echo "+++"
echo "+++ BUILDING MODULE $MODULE_PATH"
echo "+++"
cd $MODULE_PATH && {
chmod +x mvnw
./mvnw clean package
if [ $? -ne 0 ]
then
echo ""
echo "+++"
echo "+++ BUILDING MODULE $MODULE_PATH FAILED"
echo "+++"
exit 1
else
echo ""
echo "+++"
echo "+++ BUILDING MODULE $MODULE_PATH SUCCESSFUL"
echo "+++"
fi
cd $MAIN_DIR
}
}
chmod +x gradlew
build_maven_module "spring-boot/spring-boot-openapi"
build_gradle_module "spring-boot/boundaries"
build_gradle_module "spring-boot/argumentresolver"
build_gradle_module "spring-data/spring-data-jdbc-converter"
build_gradle_module "solid"
build_gradle_module "spring-boot/data-migration/flyway"
build_gradle_module "reactive"
build_gradle_module "junit/assumptions"
build_gradle_module "logging"
@@ -52,6 +84,7 @@ build_gradle_module "spring-boot/startup"
build_gradle_module "spring-boot/static"
build_gradle_module "spring-boot/validation"
build_gradle_module "spring-boot/profiles"
build_gradle_module "spring-boot/password-encoding"
build_gradle_module "spring-cloud/feign-with-spring-data-rest"
build_gradle_module "spring-cloud/sleuth-downstream-service"
build_gradle_module "spring-cloud/sleuth-upstream-service"

25
solid/build.gradle Normal file
View File

@@ -0,0 +1,25 @@
buildscript {
repositories {
jcenter()
}
}
apply plugin: 'java'
apply plugin: 'java-library'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 8
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.0.1'
testImplementation 'org.assertj:assertj-core:2.6.0'
}
test {
useJUnitPlatform()
}

BIN
solid/gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-bin.zip

172
solid/gradlew vendored Normal file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
solid/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,5 @@
package io.reflectoring.solid.isp;
interface BetterOrderService {
void submitOrder(Order order);
}

View File

@@ -0,0 +1,18 @@
package io.reflectoring.solid.isp;
class BurgerOrderService implements OrderService {
@Override
public void orderBurger(int quantity) {
System.out.println("Received order of "+quantity+" burgers");
}
@Override
public void orderFries(int fries) {
throw new UnsupportedOperationException("No fries in burger only order");
}
@Override
public void orderCombo(int quantity, int fries) {
throw new UnsupportedOperationException("No combo in burger only order");
}
}

View File

@@ -0,0 +1,18 @@
package io.reflectoring.solid.isp;
class ComboOrderService implements OrderService{
@Override
public void orderBurger(int quantity) {
System.out.println("Received order of "+quantity+" burgers");
}
@Override
public void orderFries(int fries) {
System.out.println("Received order of "+fries+ " fries");
}
@Override
public void orderCombo(int quantity, int fries) {
System.out.println("Received order of "+quantity+" burgers and "+ fries+" fries");
}
}

View File

@@ -0,0 +1,19 @@
package io.reflectoring.solid.isp;
class FriesOrderService implements OrderService {
@Override
public void orderBurger(int quantity) {
throw new UnsupportedOperationException("No burger in fries only order");
}
@Override
public void orderFries(int fries) {
System.out.println("Received order of "+fries+ " fries");
}
@Override
public void orderCombo(int quantity, int fries) {
throw new UnsupportedOperationException("No combo in fries only order");
}
}

View File

@@ -0,0 +1,10 @@
package io.reflectoring.solid.isp;
class Main{
public static void main(String[] args){
OrderService comboOrderService = new ComboOrderService();
NewBurgerOrderService burgerService =
new OrderServiceObjectAdapter(new ComboOrderService());
burgerService.orderBurger(4);
}
}

View File

@@ -0,0 +1,5 @@
package io.reflectoring.solid.isp;
interface NewBurgerOrderService {
void orderBurger(int quantity);
}

View File

@@ -0,0 +1,5 @@
package io.reflectoring.solid.isp;
interface NewFriesOrderService {
void orderFries(int fries);
}

View File

@@ -0,0 +1,5 @@
package io.reflectoring.solid.isp;
class Order {
// define order
}

View File

@@ -0,0 +1,7 @@
package io.reflectoring.solid.isp;
interface OrderService {
void orderBurger(int quantity);
void orderFries(int fries);
void orderCombo(int quantity, int fries);
}

View File

@@ -0,0 +1,14 @@
package io.reflectoring.solid.isp;
class OrderServiceObjectAdapter implements NewBurgerOrderService {
private OrderService adaptee;
public OrderServiceObjectAdapter(OrderService adaptee) {
super();
this.adaptee = adaptee;
}
@Override
public void orderBurger(int quantity) {
adaptee.orderBurger(quantity);
}
}

32
spring-boot/argumentresolver/.gitignore vendored Normal file
View File

@@ -0,0 +1,32 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,28 @@
plugins {
id 'org.springframework.boot' version '2.2.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'io.reflectoring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}
test {
useJUnitPlatform()
}

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

172
spring-boot/argumentresolver/gradlew vendored Normal file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1 @@
rootProject.name = 'argumentresolver'

View File

@@ -0,0 +1,13 @@
package io.reflectoring.argumentresolver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ArgumentresolverApplication {
public static void main(String[] args) {
SpringApplication.run(ArgumentresolverApplication.class, args);
}
}

View File

@@ -0,0 +1,15 @@
package io.reflectoring.argumentresolver;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
class ErrorHandler {
@ExceptionHandler(NotFoundException.class)
ResponseEntity<?> handleHttpStatusCodeException(NotFoundException e) {
return ResponseEntity.status(e.getStatusCode()).build();
}
}

View File

@@ -0,0 +1,12 @@
package io.reflectoring.argumentresolver;
import lombok.Value;
@Value
class GitRepository {
private final Long id;
private final String slug;
}

View File

@@ -0,0 +1,43 @@
package io.reflectoring.argumentresolver;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@RequiredArgsConstructor
class GitRepositoryArgumentResolver implements HandlerMethodArgumentResolver {
private final GitRepositoryFinder gitRepositoryFinder;
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameter().getType() == GitRepository.class;
}
@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) {
String requestPath = ((ServletWebRequest) webRequest).getRequest().getPathInfo();
String slug = requestPath
.substring(0, requestPath.indexOf("/", 1))
.replaceAll("^/", "");
Optional<GitRepository> repository = gitRepositoryFinder.findBySlug(slug);
if (repository.isEmpty()) {
throw new NotFoundException();
}
return repository.get();
}
}

View File

@@ -0,0 +1,20 @@
package io.reflectoring.argumentresolver;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
@RequiredArgsConstructor
class GitRepositoryArgumentResolverConfiguration implements WebMvcConfigurer {
private final GitRepositoryFinder gitRepositoryFinder;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new GitRepositoryArgumentResolver(gitRepositoryFinder));
}
}

View File

@@ -0,0 +1,9 @@
package io.reflectoring.argumentresolver;
import java.util.Optional;
public interface GitRepositoryFinder {
Optional<GitRepository> findBySlug(String slug);
}

View File

@@ -0,0 +1,10 @@
package io.reflectoring.argumentresolver;
import lombok.Value;
@Value
class GitRepositoryId {
private final long value;
}

View File

@@ -0,0 +1,13 @@
package io.reflectoring.argumentresolver;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
class GitRepositoryIdConverter implements Converter<String, GitRepositoryId> {
@Override
public GitRepositoryId convert(String source) {
return new GitRepositoryId(Long.parseLong(source));
}
}

View File

@@ -0,0 +1,11 @@
package io.reflectoring.argumentresolver;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpStatusCodeException;
public class NotFoundException extends HttpStatusCodeException {
protected NotFoundException() {
super(HttpStatus.NOT_FOUND);
}
}

View File

@@ -0,0 +1,43 @@
package io.reflectoring.argumentresolver;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(controllers = GitRepositoryArgumentResolverTestController.class)
class GitRepositoryArgumentResolverTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private GitRepositoryFinder gitRepositoryFinder;
@Test
void resolvesSiteSuccessfully() throws Exception {
given(gitRepositoryFinder.findBySlug("my-repo"))
.willReturn(Optional.of(new GitRepository(1L, "my-repo")));
mockMvc.perform(get("/my-repo/contributors"))
.andExpect(status().isOk());
}
@Test
void notFoundOnUnknownSlug() throws Exception {
given(gitRepositoryFinder.findBySlug("unknownSlug"))
.willReturn(Optional.empty());
mockMvc.perform(get("/unknownSlug/contributors"))
.andExpect(status().isNotFound());
}
}

View File

@@ -0,0 +1,19 @@
package io.reflectoring.argumentresolver;
import static org.assertj.core.api.Assertions.assertThat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/{repositorySlug}")
class GitRepositoryArgumentResolverTestController {
@GetMapping("/contributors")
String listContributors(GitRepository gitRepository) {
assertThat(gitRepository.getId()).isEqualTo(1L);
return "test";
}
}

View File

@@ -0,0 +1,27 @@
package io.reflectoring.argumentresolver;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(controllers = GitRepositoryIdConverterTestController.class)
class GitRepositoryIdConverterTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private GitRepositoryFinder gitRepositoryFinder;
@Test
void resolvesRepositoryId() throws Exception {
mockMvc.perform(get("/repositories/42"))
.andExpect(status().isOk());
}
}

View File

@@ -0,0 +1,18 @@
package io.reflectoring.argumentresolver;
import static org.assertj.core.api.Assertions.assertThat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
class GitRepositoryIdConverterTestController {
@GetMapping("/repositories/{repositoryId}")
String getRepository(@PathVariable("repositoryId") GitRepositoryId gitRepositoryId) {
assertThat(gitRepositoryId).isNotNull();
return "test";
}
}

32
spring-boot/boundaries/.gitignore vendored Normal file
View File

@@ -0,0 +1,32 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,30 @@
plugins {
id 'org.springframework.boot' version '2.2.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'io.reflectoring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
// ArchUnit
testImplementation 'com.tngtech.archunit:archunit-junit5:0.13.1'
testImplementation 'org.reflections:reflections:0.9.10'
}
test {
useJUnitPlatform()
}

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

172
spring-boot/boundaries/gradlew vendored Normal file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
spring-boot/boundaries/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1 @@
rootProject.name = 'boundaries'

View File

@@ -0,0 +1,13 @@
package io.reflectoring.boundaries;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BoundariesApplication {
public static void main(String[] args) {
SpringApplication.run(BoundariesApplication.class, args);
}
}

View File

@@ -0,0 +1,18 @@
package io.reflectoring.boundaries;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotate a package-info.java file with this annotation to mark it as internal, i.e. no
* classes outside of that package may depend on any classes within that package.
*/
@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InternalPackage {
}

View File

@@ -0,0 +1,11 @@
package io.reflectoring.boundaries.billing.api;
import lombok.Value;
@Value
public class Invoice {
private Long userId;
private double amount;
}

View File

@@ -0,0 +1,9 @@
package io.reflectoring.boundaries.billing.api;
import java.time.LocalDate;
public interface InvoiceCalculator {
Invoice calculateInvoice(Long userId, LocalDate fromDate, LocalDate toDate);
}

View File

@@ -0,0 +1,10 @@
package io.reflectoring.boundaries.billing.internal;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
class BillingConfiguration {
}

View File

@@ -0,0 +1,27 @@
package io.reflectoring.boundaries.billing.internal;
import io.reflectoring.boundaries.billing.api.Invoice;
import io.reflectoring.boundaries.billing.api.InvoiceCalculator;
import io.reflectoring.boundaries.billing.internal.database.api.LineItem;
import io.reflectoring.boundaries.billing.internal.database.api.ReadLineItems;
import java.time.LocalDate;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
class BillingService implements InvoiceCalculator {
private final ReadLineItems readLineItems;
@Override
public Invoice calculateInvoice(Long userId, LocalDate fromDate, LocalDate toDate) {
List<LineItem> items = readLineItems.getLineItemsForUser(userId, fromDate, toDate);
double sum = items.stream()
.mapToDouble(LineItem::getAmount)
.sum();
return new Invoice(userId, sum);
}
}

View File

@@ -0,0 +1,12 @@
package io.reflectoring.boundaries.billing.internal.batchjob.internal;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan
class BatchJobConfiguration {
}

View File

@@ -0,0 +1,42 @@
package io.reflectoring.boundaries.billing.internal.batchjob.internal;
import io.reflectoring.boundaries.billing.internal.database.api.WriteLineItems;
import io.reflectoring.boundaries.billing.internal.database.api.LineItem;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@RequiredArgsConstructor
@Component
class LoadInvoiceDataBatchJob {
private static final Logger logger = LoggerFactory.getLogger(LoadInvoiceDataBatchJob.class);
private static final Random random = new Random();
private final WriteLineItems writeLineItems;
@Scheduled(fixedRate = 5000)
void loadDataFromBillingSystem() {
List<LineItem> items = getLineItemsFromBillingSystem();
writeLineItems.saveLineItems(items);
}
private List<LineItem> getLineItemsFromBillingSystem() {
// imagine this list is loaded from a 3rd party system
return Arrays.asList(
lineItem("bread"),
lineItem("butter"),
lineItem("toilet paper")
);
}
private LineItem lineItem(String itemName) {
return new LineItem(42L, itemName, 42.42d, LocalDate.now().minusDays(random.nextInt(10)));
}
}

View File

@@ -0,0 +1,4 @@
@InternalPackage
package io.reflectoring.boundaries.billing.internal.batchjob.internal;
import io.reflectoring.boundaries.InternalPackage;

View File

@@ -0,0 +1,14 @@
package io.reflectoring.boundaries.billing.internal.database.api;
import java.time.LocalDate;
import lombok.Value;
@Value
public class LineItem {
private final Long userId;
private final String name;
private final double amount;
private final LocalDate date;
}

View File

@@ -0,0 +1,10 @@
package io.reflectoring.boundaries.billing.internal.database.api;
import java.time.LocalDate;
import java.util.List;
public interface ReadLineItems {
List<LineItem> getLineItemsForUser(Long userId, LocalDate startDate, LocalDate endDate);
}

View File

@@ -0,0 +1,9 @@
package io.reflectoring.boundaries.billing.internal.database.api;
import java.util.List;
public interface WriteLineItems {
void saveLineItems(List<LineItem> lineItems);
}

View File

@@ -0,0 +1,31 @@
package io.reflectoring.boundaries.billing.internal.database.internal;
import io.reflectoring.boundaries.billing.internal.database.api.LineItem;
import io.reflectoring.boundaries.billing.internal.database.api.ReadLineItems;
import io.reflectoring.boundaries.billing.internal.database.api.WriteLineItems;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
class BillingDatabase implements WriteLineItems, ReadLineItems {
private final LineItemRepository lineItemRepository;
@Override
public void saveLineItems(List<LineItem> lineItems) {
for (LineItem lineItem : lineItems) {
lineItemRepository.save(LineItemJpaEntity.fromDomainObject(lineItem));
}
}
@Override
public List<LineItem> getLineItemsForUser(Long userId, LocalDate startDate, LocalDate endDate) {
return lineItemRepository.findByUserIdAndDateBetween(userId, startDate, endDate).stream()
.map(LineItemJpaEntity::toDomainObject)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,12 @@
package io.reflectoring.boundaries.billing.internal.database.internal;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories
@ComponentScan
class BillingDatabaseConfiguration {
}

View File

@@ -0,0 +1,43 @@
package io.reflectoring.boundaries.billing.internal.database.internal;
import io.reflectoring.boundaries.billing.internal.database.api.LineItem;
import java.time.LocalDate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
class LineItemJpaEntity {
@Id
@GeneratedValue
private Long userId;
private String name;
private Double amount;
private LocalDate date;
static LineItemJpaEntity fromDomainObject(LineItem lineItem) {
return new LineItemJpaEntity(
lineItem.getUserId(),
lineItem.getName(),
lineItem.getAmount(),
lineItem.getDate()
);
}
LineItem toDomainObject(){
return new LineItem(
this.userId,
this.name,
this.amount,
this.date
);
}
}

View File

@@ -0,0 +1,11 @@
package io.reflectoring.boundaries.billing.internal.database.internal;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
interface LineItemRepository extends CrudRepository<LineItemJpaEntity, Long> {
List<LineItemJpaEntity> findByUserIdAndDateBetween(Long userId, LocalDate startDate, LocalDate endDate);
}

View File

@@ -0,0 +1,4 @@
@InternalPackage
package io.reflectoring.boundaries.billing.internal.database.internal;
import io.reflectoring.boundaries.InternalPackage;

View File

@@ -0,0 +1,4 @@
@InternalPackage
package io.reflectoring.boundaries.billing.internal;
import io.reflectoring.boundaries.InternalPackage;

View File

@@ -0,0 +1,13 @@
package io.reflectoring.boundaries;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BoundariesApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -0,0 +1,64 @@
package io.reflectoring.boundaries;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.reflections.Reflections;
/**
* Evaluates {@link InternalPackage} annotations and checks that those packages are not accessed from the outside.
*/
class InternalPackageTests {
private static final String BASE_PACKAGE = "io.reflectoring";
private final JavaClasses analyzedClasses = new ClassFileImporter().importPackages(BASE_PACKAGE);
@Test
void internalPackagesAreNotAccessedFromOutside() throws IOException {
// so that the test will break when the base package is re-named
assertPackageExists(BASE_PACKAGE);
List<String> internalPackages = internalPackages(BASE_PACKAGE);
for (String internalPackage : internalPackages) {
assertPackageExists(internalPackage);
assertPackageIsNotAccessedFromOutside(internalPackage);
}
}
/**
* Finds all packages annotated with @{@link InternalPackage}.
*/
private List<String> internalPackages(String basePackage) {
Reflections reflections = new Reflections(basePackage);
return reflections.getTypesAnnotatedWith(InternalPackage.class).stream()
.map(c -> c.getPackage().getName())
.collect(Collectors.toList());
}
void assertPackageIsNotAccessedFromOutside(String internalPackage) {
noClasses().that().resideOutsideOfPackage(packageMatcher(internalPackage))
.should().dependOnClassesThat().resideInAPackage(packageMatcher(internalPackage))
.check(analyzedClasses);
}
void assertPackageExists(String packageName) {
assertThat(analyzedClasses.containPackage(packageName))
.as("package %s exists", packageName)
.isTrue();
}
private String packageMatcher(String fullyQualifiedPackage) {
return fullyQualifiedPackage + "..";
}
}

View File

@@ -0,0 +1,31 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,19 @@
pipeline {
agent any
stages {
checkout scm
stage('Gradle Build') {
steps {
script {
if (isUnix()) {
sh './gradlew clean build --info'
} else {
bat 'gradlew.bat clean build --info'
}
}
}
}
}
}

View File

@@ -0,0 +1,19 @@
pipeline {
agent any
stages {
checkout scm
stage('Apply Database Migrations') {
steps {
script {
if (isUnix()) {
sh '/gradlew flywayMigrate --info'
} else {
bat 'gradlew.bat flywayMigrate --info'
}
}
}
}
}
}

View File

@@ -0,0 +1,49 @@
plugins {
id 'org.springframework.boot' version '2.2.3.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
id "org.flywaydb.flyway" version "6.2.3"
}
group = 'io.reflectoring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
compileOnly 'org.projectlombok:lombok'
// Spring
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
// Database
implementation 'org.flywaydb:flyway-core'
runtimeOnly 'com.h2database:h2'
// Add jaxb since it's no longer available in Java 11
runtime 'javax.xml.bind:jaxb-api:2.3.1'
// Test
testCompile 'org.assertj:assertj-core'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation('org.junit.jupiter:junit-jupiter:5.5.1')
}
test {
useJUnitPlatform()
}
flyway {
url = 'jdbc:h2:mem:'
locations = [
// Add this if you have Java-based migrations
'classpath:db/migration'
]
}

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#Tue Jan 21 16:55:51 EET 2020
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-all.zip
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

172
spring-boot/data-migration/flyway/gradlew vendored Executable file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1 @@
rootProject.name = 'flyway'

View File

@@ -0,0 +1,23 @@
package db.migration;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
/**
* Example of a Java-based migration using Spring {@link JdbcTemplate}.
*/
public class V2__InsertRandomUsers extends BaseJavaMigration {
public void migrate(Context context) {
final JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
// Create 10 random users
for (int i = 1; i <= 10; i++) {
jdbcTemplate.execute(String.format("insert into test_user(username, first_name, last_name) "
+ "values('%d@reflectoring.io', 'Elvis_%d', 'Presley_%d')", i, i, i));
}
}
}

View File

@@ -0,0 +1,12 @@
package io.reflectoring.flyway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FlywayApplication {
public static void main(String[] args) {
SpringApplication.run(FlywayApplication.class, args);
}
}

View File

@@ -0,0 +1 @@
DROP TABLE test_user;

View File

@@ -0,0 +1,9 @@
-- Init script
-- DDL
CREATE TABLE test_user(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL
);

View File

@@ -0,0 +1,43 @@
package io.reflectoring.flyway;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.jdbc.core.JdbcTemplate;
@DataJpaTest
class FlywayWithH2Test {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void databaseHasBeenInitialized() {
jdbcTemplate.execute("insert into test_user (username, first_name, last_name) values('reflectoring', 'Elvis', 'Presley')");
final List<AuthUser> authUsers = jdbcTemplate
.query("SELECT username, first_name, last_name FROM test_user", (rs, rowNum) -> new AuthUser(
rs.getString("username"),
rs.getString("first_name"),
rs.getString("last_name")
));
Assertions.assertThat(authUsers).isNotEmpty();
}
private static class AuthUser {
public String username;
public String firstName;
public String lastName;
public AuthUser(final String username, final String firstName, final String lastName) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
}
}
}

View File

@@ -0,0 +1,32 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,41 @@
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'io.reflectoring'
version = '0.0.1-SNAPSHOT'
description = 'password-encoding-spring-boot'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security:2.2.4.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-web:2.2.4.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.2.4.RELEASE'
implementation 'com.h2database:h2:1.4.200'
implementation 'org.flywaydb:flyway-core:6.0.8'
implementation 'org.bouncycastle:bcprov-jdk15on:1.64'
implementation 'org.projectlombok:lombok:1.18.12'
annotationProcessor 'org.projectlombok:lombok'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
implementation 'com.google.guava:guava:28.2-jre'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.2.4.RELEASE'
testImplementation 'org.springframework.security:spring-security-test:5.2.1.RELEASE'
}
test {
useJUnitPlatform()
}

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

183
spring-boot/password-encoding/gradlew vendored Normal file
View File

@@ -0,0 +1,183 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,12 @@
package io.reflectoring.passwordencoding;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PasswordEncodingSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(PasswordEncodingSpringBootApplication.class, args);
}
}

View File

@@ -0,0 +1,28 @@
package io.reflectoring.passwordencoding.authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service
public class DatabaseUserDetailPasswordService implements UserDetailsPasswordService {
private final UserRepository userRepository;
private final UserDetailsMapper userDetailsMapper;
public DatabaseUserDetailPasswordService(
UserRepository userRepository, UserDetailsMapper userDetailsMapper) {
this.userRepository = userRepository;
this.userDetailsMapper = userDetailsMapper;
}
@Override
public UserDetails updatePassword(UserDetails user, String newPassword) {
UserCredentials userCredentials = userRepository.findByUsername(user.getUsername());
userCredentials.setPassword(newPassword);
return userDetailsMapper.toUserDetails(userCredentials);
}
}

View File

@@ -0,0 +1,29 @@
package io.reflectoring.passwordencoding.authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class DatabaseUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
private final UserDetailsMapper userDetailsMapper;
public DatabaseUserDetailsService(
UserRepository userRepository, UserDetailsMapper userDetailsMapper) {
this.userRepository = userRepository;
this.userDetailsMapper = userDetailsMapper;
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
UserCredentials userCredentials = userRepository.findByUsername(username);
return userDetailsMapper.toUserDetails(userCredentials);
}
}

View File

@@ -0,0 +1,31 @@
package io.reflectoring.passwordencoding.authentication;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Set;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "users")
public class UserCredentials {
@Id private String username;
private String password;
boolean enabled;
@ElementCollection
@JoinTable(
name = "authorities",
joinColumns = {@JoinColumn(name = "username")})
@Column(name = "authority")
private Set<String> roles;
}

View File

@@ -0,0 +1,17 @@
package io.reflectoring.passwordencoding.authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
@Component
class UserDetailsMapper {
UserDetails toUserDetails(UserCredentials userCredentials) {
return User.withUsername(userCredentials.getUsername())
.password(userCredentials.getPassword())
.roles(userCredentials.getRoles().toArray(String[]::new))
.build();
}
}

View File

@@ -0,0 +1,10 @@
package io.reflectoring.passwordencoding.authentication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface UserRepository extends JpaRepository<UserCredentials, String> {
UserCredentials findByUsername(String username);
}

View File

@@ -0,0 +1,82 @@
package io.reflectoring.passwordencoding.configuration;
import io.reflectoring.passwordencoding.authentication.DatabaseUserDetailPasswordService;
import io.reflectoring.passwordencoding.authentication.DatabaseUserDetailsService;
import io.reflectoring.passwordencoding.workfactor.BcCryptWorkFactorService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.*;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableWebSecurity
class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final BcCryptWorkFactorService bcCryptWorkFactorService;
private final DatabaseUserDetailsService databaseUserDetailsService;
private final DatabaseUserDetailPasswordService databaseUserDetailPasswordService;
public SecurityConfiguration(
BcCryptWorkFactorService bcCryptWorkFactorService,
DatabaseUserDetailsService databaseUserDetailsService,
DatabaseUserDetailPasswordService databaseUserDetailPasswordService) {
this.bcCryptWorkFactorService = bcCryptWorkFactorService;
this.databaseUserDetailsService = databaseUserDetailsService;
this.databaseUserDetailPasswordService = databaseUserDetailPasswordService;
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/registration")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
httpSecurity.headers().frameOptions().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
// we must use deprecated encoder to support their encoding
String encodingId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(encodingId, new BCryptPasswordEncoder(bcCryptWorkFactorService.calculateStrength()));
encoders.put("ldap", new LdapShaPasswordEncoder());
encoders.put("MD4", new Md4PasswordEncoder());
encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("SHA-1", new MessageDigestPasswordEncoder("SHA-1"));
encoders.put("SHA-256", new MessageDigestPasswordEncoder("SHA-256"));
encoders.put("sha256", new StandardPasswordEncoder());
encoders.put("argon2", new Argon2PasswordEncoder());
return new DelegatingPasswordEncoder(encodingId, encoders);
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsPasswordService(this.databaseUserDetailPasswordService);
provider.setUserDetailsService(this.databaseUserDetailsService);
return provider;
}
}

View File

@@ -0,0 +1,18 @@
package io.reflectoring.passwordencoding.encoder;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
class Argon2Example {
public String encode(String plainPassword) {
int saltLength = 16; // salt length in bytes
int hashLength = 32; // hash length in bytes
int parallelism = 1; // currently is not supported
int memory = 4096; // memory costs
int iterations = 3;
Argon2PasswordEncoder argon2PasswordEncoder =
new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations);
return argon2PasswordEncoder.encode(plainPassword);
}
}

View File

@@ -0,0 +1,15 @@
package io.reflectoring.passwordencoding.encoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.security.SecureRandom;
class BCryptExample {
public String encode(String plainPassword) {
int strength = 10;
BCryptPasswordEncoder bCryptPasswordEncoder =
new BCryptPasswordEncoder(strength, new SecureRandom());
return bCryptPasswordEncoder.encode(plainPassword);
}
}

View File

@@ -0,0 +1,17 @@
package io.reflectoring.passwordencoding.encoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
class Pbkdf2Example {
public String encode(String plainPassword) {
String pepper = "pepper"; // secret key used by password encoding
int iterations = 200000; // number of hash iteration
int hashWidth = 256; // hash with in bits
Pbkdf2PasswordEncoder pbkdf2PasswordEncoder =
new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth);
return pbkdf2PasswordEncoder.encode(plainPassword);
}
}

View File

@@ -0,0 +1,18 @@
package io.reflectoring.passwordencoding.encoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
class SCryptExample {
public String encode(String plainPassword) {
int cpuCost = (int) Math.pow(2, 14); // factor to increase CPU costs
int memoryCost = 8; // factor to increases memory usage
int parallelization = 1; // currently nor supported by Spring Security
int keyLength = 32; // key length in bytes
int saltLength = 64; // salt length in bytes
SCryptPasswordEncoder sCryptPasswordEncoder =
new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength);
return sCryptPasswordEncoder.encode(plainPassword);
}
}

View File

@@ -0,0 +1,16 @@
package io.reflectoring.passwordencoding.resources;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Data
@Builder
@AllArgsConstructor
class Car {
private String name;
private String color;
}

View File

@@ -0,0 +1,15 @@
package io.reflectoring.passwordencoding.resources;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;
@RestController
class CarResources {
@GetMapping("/cars")
public Set<Car> cars() {
return Set.of(new Car("vw", "black"), new Car("bmw", "white"));
}
}

View File

@@ -0,0 +1,37 @@
package io.reflectoring.passwordencoding.resources;
import io.reflectoring.passwordencoding.authentication.UserCredentials;
import io.reflectoring.passwordencoding.authentication.UserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;
@RestController
class RegistrationResource {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public RegistrationResource(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@PostMapping("/registration")
@ResponseStatus(code = HttpStatus.CREATED)
public void register(@RequestBody UserCredentialsDto userCredentialsDto) {
UserCredentials user =
UserCredentials.builder()
.enabled(true)
.username(userCredentialsDto.getUsername())
.password(passwordEncoder.encode(userCredentialsDto.getPassword()))
.roles(Set.of("USER"))
.build();
userRepository.save(user);
}
}

View File

@@ -0,0 +1,15 @@
package io.reflectoring.passwordencoding.resources;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class UserCredentialsDto {
private String username;
private String password;
}

View File

@@ -0,0 +1,101 @@
package io.reflectoring.passwordencoding.workfactor;
import com.google.common.base.Stopwatch;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class BcCryptWorkFactorService {
private static final String TEST_PASSWORD = "my password";
private static final int GOAL_MILLISECONDS_PER_PASSWORD = 1000;
private static final int MIN_STRENGTH = 4;
private static final int MAX_STRENGTH = 31;
/**
* Calculates the strength (a.k.a. log rounds) for the BCrypt Algorithm, so that password encoding
* takes about 1s. This method uses the divide-and-conquer algorithm.
*/
public BcryptWorkFactor calculateStrengthDivideAndConquer() {
return calculateStrengthDivideAndConquer(
new BcryptWorkFactor(MIN_STRENGTH, Integer.MIN_VALUE),
new BcryptWorkFactor(MAX_STRENGTH, Integer.MAX_VALUE));
}
private BcryptWorkFactor calculateStrengthDivideAndConquer(
BcryptWorkFactor smallFactor, BcryptWorkFactor bigFactor) {
if (bigFactor.getStrength() - smallFactor.getStrength() == 1) {
return getClosestStrength(smallFactor, bigFactor);
}
int midStrength =
(bigFactor.getStrength() - smallFactor.getStrength()) / 2 + smallFactor.getStrength();
long duration = calculateDuration(midStrength);
BcryptWorkFactor midFactor = new BcryptWorkFactor(midStrength, duration);
if (duration < GOAL_MILLISECONDS_PER_PASSWORD) {
return calculateStrengthDivideAndConquer(midFactor, bigFactor);
}
return calculateStrengthDivideAndConquer(smallFactor, midFactor);
}
private BcryptWorkFactor getClosestStrength(
BcryptWorkFactor smallFactor, BcryptWorkFactor bigFactor) {
if (isPreviousDurationCloserToGoal(smallFactor.getDuration(), bigFactor.getDuration())) {
return smallFactor;
}
return bigFactor;
}
private long calculateDuration(int strength) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength);
Stopwatch stopwatch = Stopwatch.createStarted();
bCryptPasswordEncoder.encode(TEST_PASSWORD);
stopwatch.stop();
return stopwatch.elapsed(TimeUnit.MILLISECONDS);
}
/**
* Calculates the strength (a.k.a. log rounds) for the BCrypt Algorithm, so that password encoding
* takes about 1s. This method iterates over strength from 4 to 31 and calculates the duration of
* password encoding for every value of strength. It returns the first strength, that takes more
* than 1s
*/
public int calculateStrength() {
for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) {
long duration = calculateDuration(strength);
if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) {
return strength;
}
}
throw new RuntimeException(
String.format(
"Could not find suitable round number for bcrypt encoding. The encoding with %d rounds"
+ " takes less than %d ms.",
MAX_STRENGTH, GOAL_MILLISECONDS_PER_PASSWORD));
}
/**
* @param previousDuration duration from previous iteration
* @param currentDuration duration of current iteration
* @param strength current strength
* @return return the current strength, if current duration is closer to
* GOAL_MILLISECONDS_PER_PASSWORD, otherwise current strength-1.
*/
int getStrength(long previousDuration, long currentDuration, int strength) {
if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) {
return strength - 1;
} else {
return strength;
}
}
/**
* return true, if previousDuration is closer to the goal than currentDuration, false otherwise.
*/
boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) {
return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration)
< Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration);
}
}

View File

@@ -0,0 +1,12 @@
package io.reflectoring.passwordencoding.workfactor;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
class BcryptWorkFactor {
private int strength;
private long duration;
}

Some files were not shown because too many files have changed in this diff Show More