├── .DS_Store ├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── LICENSE ├── Procfile ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── pushToHeroku.sh └── src ├── main ├── java │ └── com │ │ └── tomekl007 │ │ ├── PaymentApplication.java │ │ ├── chapter_1 │ │ ├── AvoidRuntimeClash.java │ │ ├── ConstructorInjection.java │ │ ├── FavorComposition.java │ │ ├── PitfallFieldInjection.java │ │ ├── UsingScope.java │ │ ├── UsingScopeSecond.java │ │ └── beans │ │ │ ├── ChildBean.java │ │ │ ├── ComposeBean.java │ │ │ ├── ExternalService.java │ │ │ ├── ParentBean.java │ │ │ ├── PrototypeBean.java │ │ │ ├── RESTExternalService.java │ │ │ ├── SOAPExternalService.java │ │ │ └── SingletonBean.java │ │ ├── chapter_2 │ │ ├── ConfigInheritance.java │ │ ├── SpecificService.java │ │ ├── SpecificServiceSettings.java │ │ ├── SpringProfilesTest.java │ │ └── profilesconfig │ │ │ ├── DataSourceConfig.java │ │ │ ├── DefaultDataSourceConfig.java │ │ │ ├── DevDataSourceConfig.java │ │ │ └── ProductionDataSourceConfig.java │ │ ├── chapter_3 │ │ ├── api │ │ │ ├── PaymentController.java │ │ │ ├── PropagatesExceptionEndpoint.java │ │ │ └── RESTErrorHandlingController.java │ │ ├── domain │ │ │ ├── Payment.java │ │ │ ├── PaymentAndUser.java │ │ │ ├── PaymentDto.java │ │ │ ├── User.java │ │ │ └── UserDto.java │ │ └── persistance │ │ │ ├── PaymentRepository.java │ │ │ ├── PaymentRestRepository.java │ │ │ ├── ReactivePaymentService.java │ │ │ └── UsersRepository.java │ │ ├── chapter_6 │ │ ├── FacebookService.java │ │ ├── PaymentDetailsWithFallback.java │ │ ├── RestTemplateConfiguration.java │ │ └── retry │ │ │ ├── DefaultListenerSupport.java │ │ │ └── RetryTemplateConfiguration.java │ │ ├── eventbus │ │ ├── api │ │ │ └── EventBus.java │ │ ├── domain │ │ │ └── Event.java │ │ └── infrastructure │ │ │ └── InMemoryEventBus.java │ │ ├── metrics │ │ ├── MetricsSetup.java │ │ └── MetrricsCustomController.java │ │ ├── notifications │ │ ├── api │ │ │ └── NotificationController.java │ │ ├── domain │ │ │ ├── HelloMessage.java │ │ │ └── PaymentAddedNotification.java │ │ └── infrastructure │ │ │ └── WebSocketConfig.java │ │ └── payment │ │ ├── api │ │ ├── MVCController.java │ │ ├── PaymentService.java │ │ ├── UserService.java │ │ └── rest │ │ │ └── UserController.java │ │ ├── details │ │ └── api │ │ │ ├── PaymentDetails.java │ │ │ └── PaymentDetailsController.java │ │ ├── infrastructure │ │ ├── audit │ │ │ └── LoggingAspect.java │ │ ├── configuration │ │ │ ├── FilterConfig.java │ │ │ └── PaymentServiceSettings.java │ │ ├── exceptions │ │ │ └── UserNotFoundException.java │ │ ├── filter │ │ │ ├── InterceptRequestResponseFilter.java │ │ │ └── TransactionFilter.java │ │ ├── healtchecks │ │ │ └── DownstreamHealthcheck.java │ │ └── security │ │ │ ├── SecretController.java │ │ │ ├── SpringSecurityWebAppConfig.java │ │ │ └── SpringSecurityWebAppConfigWithCsrf.java │ │ └── service │ │ ├── ExternalPaymentService.java │ │ ├── TransactionService.java │ │ └── UserServiceImpl.java └── resources │ ├── application-dev.yml │ ├── application.yml │ ├── docker_build.sh │ ├── log4j.properties │ ├── static │ ├── app.js │ ├── index.html │ └── main.css │ ├── status_endoints.sh │ └── templates │ ├── allPayments.html │ └── create.html └── test └── java └── com └── tomekl007 ├── PaymentDetailsMock.java ├── chapter_3 └── PaymentRepositoryIntegrationTest.java ├── chapter_5 ├── MVCControllerSecurityTest.java ├── MVCControllerTest.java ├── ReactivePaymentServiceIntegrationTest.java └── ReactivePaymentServiceLiveTest.java ├── chapter_6 └── SpringRetryTest.java └── chapter_7 ├── MicroMeterCacheSize.java └── ResponseTimesHistogramTest.java /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Spring-Boot-Tips-Tricks-and-Techniques/eb34a7d098d4ee1baa1f237ece8e1423b6db6ce4/.DS_Store -------------------------------------------------------------------------------- /.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/ 25 | 26 | 27 | 28 | # Created by https://www.gitignore.io/api/java,maven,intellij 29 | # Edit at https://www.gitignore.io/?templates=java,maven,intellij 30 | 31 | ### Intellij ### 32 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 33 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 34 | 35 | # User-specific stuff 36 | .idea/**/workspace.xml 37 | .idea/**/tasks.xml 38 | .idea/**/usage.statistics.xml 39 | .idea/**/dictionaries 40 | .idea/**/shelf 41 | 42 | # Generated files 43 | .idea/**/contentModel.xml 44 | 45 | # Sensitive or high-churn files 46 | .idea/**/dataSources/ 47 | .idea/**/dataSources.ids 48 | .idea/**/dataSources.local.xml 49 | .idea/**/sqlDataSources.xml 50 | .idea/**/dynamic.xml 51 | .idea/**/uiDesigner.xml 52 | .idea/**/dbnavigator.xml 53 | 54 | # Gradle 55 | .idea/**/gradle.xml 56 | .idea/**/libraries 57 | 58 | # Gradle and Maven with auto-import 59 | # When using Gradle or Maven with auto-import, you should exclude module files, 60 | # since they will be recreated, and may cause churn. Uncomment if using 61 | # auto-import. 62 | # .idea/modules.xml 63 | # .idea/*.iml 64 | # .idea/modules 65 | 66 | # CMake 67 | cmake-build-*/ 68 | 69 | # Mongo Explorer plugin 70 | .idea/**/mongoSettings.xml 71 | 72 | # File-based project format 73 | *.iws 74 | 75 | # IntelliJ 76 | out/ 77 | 78 | # mpeltonen/sbt-idea plugin 79 | .idea_modules/ 80 | 81 | # JIRA plugin 82 | atlassian-ide-plugin.xml 83 | 84 | # Cursive Clojure plugin 85 | .idea/replstate.xml 86 | 87 | # Crashlytics plugin (for Android Studio and IntelliJ) 88 | com_crashlytics_export_strings.xml 89 | crashlytics.properties 90 | crashlytics-build.properties 91 | fabric.properties 92 | 93 | # Editor-based Rest Client 94 | .idea/httpRequests 95 | 96 | # Android studio 3.1+ serialized cache file 97 | .idea/caches/build_file_checksums.ser 98 | 99 | ### Intellij Patch ### 100 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 101 | 102 | # *.iml 103 | # modules.xml 104 | # .idea/misc.xml 105 | # *.ipr 106 | 107 | # Sonarlint plugin 108 | .idea/sonarlint 109 | 110 | ### Java ### 111 | # Compiled class file 112 | *.class 113 | 114 | # Log file 115 | *.log 116 | 117 | # BlueJ files 118 | *.ctxt 119 | 120 | # Mobile Tools for Java (J2ME) 121 | .mtj.tmp/ 122 | 123 | # Package Files # 124 | *.jar 125 | *.war 126 | *.nar 127 | *.ear 128 | *.zip 129 | *.tar.gz 130 | *.rar 131 | 132 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 133 | hs_err_pid* 134 | 135 | ### Maven ### 136 | target/ 137 | pom.xml.tag 138 | pom.xml.releaseBackup 139 | pom.xml.versionsBackup 140 | pom.xml.next 141 | release.properties 142 | dependency-reduced-pom.xml 143 | buildNumber.properties 144 | .mvn/timing.properties 145 | .mvn/wrapper/maven-wrapper.jar 146 | 147 | # End of https://www.gitignore.io/api/java,maven,intellij 148 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: java $JAVA_OPTS -Dserver.port=$PORT -jar target/*.jar 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot: Tips, Tricks, and Techniques [Video] 2 | This is the code repository for [Spring Boot: Tips, Tricks, and Techniques [Video]](https://www.packtpub.com/programming/spring-boot-tips-tricks-and-techniques-video), published by [Packt](https://www.packtpub.com/?utm_source=github). It contains all the supporting project files necessary to work through the video course from start to finish. 3 | ## About the Video Course 4 | This course sets out to supply new possibilities. You will cover many aspects of Spring Boots: some you may know, and some you probably never knew existed. This course will boost your skills and will let you explore best practices and techniques to help you improve your application development. 5 | In this course, you'll learn to implement practical and proven techniques and adopt a quicker way to develop applications using Spring Boot. Each section covers techniques (with clear instructions) you can use to carry out different development tasks in a practical manner. We cover how to make your apps more maintainable, testable, fault-tolerant, and resilient. 6 | By the end of this course, you will have the knowledge and confidence to harness the Spring Boot tips, best practices, and techniques covered in the course to make your coding and app development projects achieve their maximum potential performance-wise. 7 |

What You Will Learn

8 |
9 |
19 | 20 | ### Technical Requirements 21 | For successful completion of this course, students will require the computer systems with at least the following:
22 | • IntelliJ IDEA
23 | • Java JDK 8 or later
24 | 25 | 26 | ### Recommended Hardware Requirements:
27 | For an optimal experience with hands-on labs and other practical activities, we recommend the following configuration: 28 |
29 | • Processor: I7 2.8
30 | • Memory: 16GB
31 | • Hard Disk Space: 200MB
32 | • Video Card: 256MB Video Memory 33 | 34 | 35 | 36 | 37 | ## Related Products 38 | * [Hands-On Application Development with Spring Boot 2 [Video]](https://www.packtpub.com/application-development/hands-application-development-spring-boot-2-video) 39 | 40 | * [Hands-On Microservices with Spring Boot 2.0 [Video]](https://www.packtpub.com/application-development/hands-microservices-spring-boot-20-video) 41 | 42 | * [Hands-On Spring Security 5.x [Video]](https://www.packtpub.com/application-development/hands-spring-security-5x-video) 43 | 44 | -------------------------------------------------------------------------------- /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.tomekl007 7 | hands-on-app-developement-spring 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | packt 12 | Spring-app 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.0.M3 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.M1 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-actuator 32 | 33 | 34 | org.springframework.metrics 35 | spring-metrics 36 | 0.5.1.RELEASE 37 | 38 | 39 | io.prometheus 40 | simpleclient_common 41 | 0.5.0 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-aop 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-cloud-connectors 50 | 51 | 52 | org.springframework.cloud 53 | spring-cloud-starter-eureka 54 | 55 | 56 | org.springframework.cloud 57 | spring-cloud-starter-eureka-server 58 | 59 | 60 | org.springframework.cloud 61 | spring-cloud-starter-hystrix 62 | 63 | 64 | org.springframework.cloud 65 | spring-cloud-starter-hystrix-dashboard 66 | 67 | 68 | org.springframework.cloud 69 | spring-cloud-starter-ribbon 70 | 71 | 72 | org.springframework.cloud 73 | spring-cloud-starter 74 | 75 | 76 | io.projectreactor 77 | reactor-core 78 | 79 | 80 | org.springframework.boot 81 | spring-boot-starter-data-jpa 82 | 83 | 84 | org.springframework.boot 85 | spring-boot-starter-data-rest 86 | 87 | 88 | org.springframework.boot 89 | spring-boot-starter-jersey 90 | 91 | 92 | org.springframework.boot 93 | spring-boot-starter-webflux 94 | 95 | 96 | org.springframework.boot 97 | spring-boot-starter-security 98 | 99 | 100 | org.springframework.boot 101 | spring-boot-starter-thymeleaf 102 | 103 | 104 | org.springframework.boot 105 | spring-boot-starter-web 106 | 107 | 108 | org.springframework.boot 109 | spring-boot-starter-webflux 110 | 111 | 112 | org.springframework.boot 113 | spring-boot-starter-websocket 114 | 115 | 116 | 117 | org.springframework.boot 118 | spring-boot-configuration-processor 119 | true 120 | 121 | 122 | org.springframework.boot 123 | spring-boot-test 124 | 125 | 126 | org.springframework.retry 127 | spring-retry 128 | 129 | 130 | 131 | com.h2database 132 | h2 133 | runtime 134 | 135 | 136 | org.springframework.boot 137 | spring-boot-starter-test 138 | test 139 | 140 | 141 | io.projectreactor 142 | reactor-test 143 | test 144 | 145 | 146 | org.springframework.security 147 | spring-security-test 148 | test 149 | 150 | 151 | 152 | 153 | org.webjars 154 | webjars-locator 155 | 156 | 157 | org.webjars 158 | sockjs-client 159 | 1.0.2 160 | 161 | 162 | org.webjars 163 | stomp-websocket 164 | 2.3.3 165 | 166 | 167 | org.webjars 168 | bootstrap 169 | 3.3.7 170 | 171 | 172 | org.webjars 173 | jquery 174 | 3.1.0 175 | 176 | 177 | 178 | 179 | 180 | 181 | org.springframework.cloud 182 | spring-cloud-dependencies 183 | ${spring-cloud.version} 184 | pom 185 | import 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | org.springframework.boot 194 | spring-boot-maven-plugin 195 | 196 | 197 | com.spotify 198 | docker-maven-plugin 199 | 1.2.0 200 | 201 | hands-on-spring-packt-docker-image 202 | java 203 | ["java", "-jar", "/${project.build.finalName}.jar"] 204 | 205 | 206 | 207 | / 208 | ${project.build.directory} 209 | ${project.build.finalName}.jar 210 | 211 | 212 | 213 | 214 | 215 | org.apache.maven.plugins 216 | maven-compiler-plugin 217 | 218 | 8 219 | 8 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | spring-snapshots 228 | Spring Snapshots 229 | https://repo.spring.io/snapshot 230 | 231 | true 232 | 233 | 234 | 235 | spring-milestones 236 | Spring Milestones 237 | https://repo.spring.io/milestone 238 | 239 | false 240 | 241 | 242 | 243 | 244 | 245 | 246 | spring-snapshots 247 | Spring Snapshots 248 | https://repo.spring.io/snapshot 249 | 250 | true 251 | 252 | 253 | 254 | spring-milestones 255 | Spring Milestones 256 | https://repo.spring.io/milestone 257 | 258 | false 259 | 260 | 261 | 262 | 263 | 264 | 265 | -------------------------------------------------------------------------------- /pushToHeroku.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | git push -f heroku HEAD:master -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/PaymentApplication.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007; 2 | 3 | import com.tomekl007.payment.api.PaymentService; 4 | import io.prometheus.client.CollectorRegistry; 5 | import org.apache.http.client.HttpClient; 6 | import org.apache.http.client.config.RequestConfig; 7 | import org.apache.http.impl.client.CloseableHttpClient; 8 | import org.apache.http.impl.client.HttpClientBuilder; 9 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.SpringApplication; 12 | import org.springframework.boot.actuate.endpoint.PublicMetrics; 13 | import org.springframework.boot.autoconfigure.SpringBootApplication; 14 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 15 | import org.springframework.cloud.netflix.hystrix.EnableHystrix; 16 | import org.springframework.context.annotation.Bean; 17 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 18 | import org.springframework.context.annotation.Primary; 19 | import org.springframework.core.env.AbstractEnvironment; 20 | import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 21 | import org.springframework.metrics.export.prometheus.EnablePrometheusMetrics; 22 | import org.springframework.metrics.instrument.prometheus.PrometheusMeterRegistry; 23 | import org.springframework.web.client.RestTemplate; 24 | 25 | import java.util.Collection; 26 | 27 | @SpringBootApplication 28 | @EnableAspectJAutoProxy 29 | @EnableHystrix 30 | @EnablePrometheusMetrics 31 | public class PaymentApplication { 32 | @Autowired(required = false) 33 | PaymentService paymentService; 34 | 35 | public static void main(String[] args) { 36 | //you can use -Dspring.profiles.active=dev when starting app instead of hardcoding it 37 | System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev"); 38 | 39 | SpringApplication.run(PaymentApplication.class, args); 40 | } 41 | 42 | 43 | //this is instead of XML based config 44 | @Bean 45 | @ConditionalOnMissingBean 46 | CollectorRegistry collectorRegistry() { 47 | CollectorRegistry collectorRegistry = new CollectorRegistry(); 48 | return collectorRegistry; 49 | } 50 | 51 | @Bean 52 | @Primary 53 | PrometheusMeterRegistry meterRegistry() { 54 | return new PrometheusMeterRegistry(collectorRegistry()); 55 | } 56 | 57 | static { 58 | //HACK Avoids duplicate metrics registration in case of Spring Boot dev-tools restarts 59 | CollectorRegistry.defaultRegistry.clear(); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/AvoidRuntimeClash.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1; 2 | 3 | import com.tomekl007.chapter_1.beans.ExternalService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class AvoidRuntimeClash { 10 | 11 | private final ExternalService externalService; 12 | 13 | //will fail with: 14 | //Parameter 0 of constructor in com.tomekl007.chapter_1.AvoidRuntimeClash required a single bean, but 2 were found: 15 | // @Autowired 16 | // public AvoidRuntimeClash(@ExternalService externalService) { 17 | // this.externalService = externalService; 18 | // externalService.call(); 19 | // } 20 | 21 | @Autowired 22 | public AvoidRuntimeClash(@Qualifier("RESTExternalService") ExternalService externalService) { 23 | this.externalService = externalService; 24 | externalService.call(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/ConstructorInjection.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1; 2 | 3 | import com.tomekl007.payment.api.PaymentService; 4 | import com.tomekl007.chapter_3.domain.Payment; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class ConstructorInjection { 10 | 11 | 12 | private final PaymentService paymentService; 13 | 14 | @Autowired 15 | private ConstructorInjection(PaymentService paymentService) { 16 | this.paymentService = paymentService; 17 | paymentService.pay(new Payment());//we can do it 18 | } 19 | 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/FavorComposition.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1; 2 | 3 | import com.tomekl007.chapter_1.beans.ChildBean; 4 | import com.tomekl007.chapter_1.beans.ComposeBean; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class FavorComposition { 10 | 11 | private final ChildBean childBean; 12 | private final ComposeBean composeBean; 13 | 14 | @Autowired 15 | public FavorComposition(ChildBean childBean, ComposeBean composeBean) { 16 | this.childBean = childBean; 17 | this.composeBean = composeBean; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/PitfallFieldInjection.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1; 2 | 3 | 4 | import com.tomekl007.payment.api.PaymentService; 5 | import com.tomekl007.chapter_3.domain.Payment; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | 8 | //@Component 9 | public class PitfallFieldInjection { 10 | 11 | @Autowired 12 | private PaymentService paymentService; 13 | 14 | private PitfallFieldInjection(){ 15 | paymentService.pay(new Payment());//problem!! 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/UsingScope.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1; 2 | 3 | import com.tomekl007.chapter_1.beans.PrototypeBean; 4 | import com.tomekl007.chapter_1.beans.SingletonBean; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class UsingScope { 10 | private final SingletonBean singletonBean; 11 | private final PrototypeBean prototypeBean; 12 | 13 | 14 | @Autowired 15 | public UsingScope(SingletonBean singletonBean, PrototypeBean prototypeBean) { 16 | System.out.println("creating UsingScope"); 17 | this.singletonBean = singletonBean; 18 | this.prototypeBean = prototypeBean; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/UsingScopeSecond.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1; 2 | 3 | import com.tomekl007.chapter_1.beans.PrototypeBean; 4 | import com.tomekl007.chapter_1.beans.SingletonBean; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class UsingScopeSecond { 10 | private final SingletonBean singletonBean; 11 | private final PrototypeBean prototypeBean; 12 | 13 | 14 | @Autowired 15 | public UsingScopeSecond(SingletonBean singletonBean, PrototypeBean prototypeBean) { 16 | System.out.println("creating UsingScopeSecond"); 17 | this.singletonBean = singletonBean; 18 | this.prototypeBean = prototypeBean; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/ChildBean.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | @Component 6 | public class ChildBean extends ParentBean { 7 | // we need to worry about lifecycle of ParentBean and ChildBean 8 | 9 | @Override 10 | public void action() { 11 | System.out.println("Action from ChildBean"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/ComposeBean.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class ComposeBean { 8 | // Spring is taking care of lifecycle of all components 9 | // We don't need to worry about initialization order; 10 | private final ParentBean parentBean; 11 | 12 | @Autowired 13 | public ComposeBean(ParentBean parentBean) { 14 | this.parentBean = parentBean; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/ExternalService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | public interface ExternalService { 4 | void call(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/ParentBean.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | @Component 6 | public class ParentBean { 7 | public void action(){ 8 | System.out.println("Action from parent"); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/PrototypeBean.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | import org.springframework.context.annotation.Scope; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @Scope("prototype") 8 | public class PrototypeBean { 9 | 10 | public PrototypeBean() { 11 | System.out.println("constructor of PrototypeBean"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/RESTExternalService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class RESTExternalService implements ExternalService { 8 | @Override 9 | public void call() { 10 | System.out.println("call RESTExternalService"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/SOAPExternalService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | @Component 6 | public class SOAPExternalService implements ExternalService{ 7 | @Override 8 | public void call() { 9 | System.out.println("call SOAPExternalService"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_1/beans/SingletonBean.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_1.beans; 2 | 3 | import org.springframework.context.annotation.Scope; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @Scope("singleton") 8 | public class SingletonBean { 9 | public SingletonBean() { 10 | System.out.println("constructor of SingletonBean"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/ConfigInheritance.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | import javax.annotation.PostConstruct; 9 | 10 | @Component 11 | public class ConfigInheritance { 12 | private final static Logger LOG = LoggerFactory.getLogger(ConfigInheritance.class); 13 | private final SpecificServiceSettings specificServiceSettings; 14 | 15 | @Autowired 16 | public ConfigInheritance(SpecificServiceSettings specificServiceSettings) { 17 | this.specificServiceSettings = specificServiceSettings; 18 | } 19 | @PostConstruct 20 | public void logSettings(){ 21 | LOG.info("starting ConfigInheritance, current config is: {}", specificServiceSettings); 22 | // Validate behaviour when starting with -Dspring.profiles.active=prod 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/SpecificService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class SpecificService { 8 | private final SpecificServiceSettings specificServiceSettings; 9 | 10 | @Autowired 11 | // Inject fine-grained config for this specific service - easy to "mock" and test. 12 | public SpecificService(SpecificServiceSettings specificServiceSettings) { 13 | this.specificServiceSettings = specificServiceSettings; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/SpecificServiceSettings.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @ConfigurationProperties(prefix = "service-config") 8 | public class SpecificServiceSettings { 9 | private Integer a; 10 | private String b; 11 | 12 | public Integer getA() { 13 | return a; 14 | } 15 | 16 | public void setA(Integer a) { 17 | this.a = a; 18 | } 19 | 20 | public String getB() { 21 | return b; 22 | } 23 | 24 | public void setB(String b) { 25 | this.b = b; 26 | } 27 | 28 | @Override 29 | public String 30 | toString() { 31 | return "SpecificServiceSettings{" + 32 | "a=" + a + 33 | ", b='" + b + '\'' + 34 | '}'; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/SpringProfilesTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2; 2 | 3 | import com.tomekl007.chapter_2.profilesconfig.DataSourceConfig; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.annotation.PostConstruct; 8 | 9 | @Component 10 | public class SpringProfilesTest { 11 | 12 | private final DataSourceConfig dataSourceConfig; 13 | 14 | @Autowired 15 | public SpringProfilesTest(DataSourceConfig dataSourceConfig) { 16 | this.dataSourceConfig = dataSourceConfig; 17 | } 18 | 19 | @PostConstruct 20 | public void setupDatasource() { 21 | dataSourceConfig.setup(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/profilesconfig/DataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2.profilesconfig; 2 | 3 | public interface DataSourceConfig { 4 | public void setup(); 5 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/profilesconfig/DefaultDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2.profilesconfig; 2 | 3 | import org.springframework.context.annotation.Profile; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @Profile("integration") 8 | public class DefaultDataSourceConfig implements DataSourceConfig { 9 | @Override 10 | public void setup() { 11 | System.out.println("Setting up dataSource for INTEGRATION environment. "); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/profilesconfig/DevDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2.profilesconfig; 2 | 3 | import com.tomekl007.chapter_2.profilesconfig.DataSourceConfig; 4 | import org.springframework.context.annotation.Profile; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | @Profile("dev") 9 | public class DevDataSourceConfig implements DataSourceConfig { 10 | @Override 11 | public void setup() { 12 | System.out.println("Setting up dataSource for DEV environment. "); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_2/profilesconfig/ProductionDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_2.profilesconfig; 2 | 3 | import org.springframework.context.annotation.Profile; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @Profile("prod") 8 | public class ProductionDataSourceConfig implements DataSourceConfig { 9 | @Override 10 | public void setup() { 11 | System.out.println("Setting up dataSource for PRODUCTION environment. "); 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/api/PaymentController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.api; 2 | 3 | import com.tomekl007.chapter_3.domain.PaymentDto; 4 | import com.tomekl007.chapter_3.persistance.ReactivePaymentService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.metrics.instrument.DistributionSummary; 7 | import org.springframework.metrics.instrument.MeterRegistry; 8 | import org.springframework.metrics.instrument.Timer; 9 | import org.springframework.metrics.instrument.stats.hist.NormalHistogram; 10 | import org.springframework.metrics.instrument.stats.quantile.GKQuantiles; 11 | import org.springframework.web.bind.annotation.*; 12 | import reactor.core.publisher.Mono; 13 | 14 | import javax.ws.rs.core.MediaType; 15 | import java.util.List; 16 | 17 | @RestController() 18 | public class PaymentController { 19 | 20 | private final ReactivePaymentService paymentRepository; 21 | private final DistributionSummary distributionSummary; 22 | private final Timer postTimer; 23 | 24 | @Autowired 25 | public PaymentController(ReactivePaymentService paymentRepository, 26 | MeterRegistry meterRegistry) { 27 | this.paymentRepository = paymentRepository; 28 | postTimer = meterRegistry 29 | .timerBuilder("payment_create") 30 | .quantiles(GKQuantiles.quantiles(0.99, 0.90, 0.80, 0.50).create()).create(); 31 | 32 | distributionSummary = meterRegistry.summaryBuilder("user_id_length") 33 | .histogram( 34 | new NormalHistogram(NormalHistogram.linear(0, 5, 10)) 35 | ) 36 | .create(); 37 | } 38 | 39 | @GetMapping("/reactive/payment/{userId}") 40 | public Mono> getPayments(@PathVariable final String userId) { 41 | distributionSummary.record(userId.length()); 42 | return paymentRepository.getPayments(userId); 43 | } 44 | 45 | @PostMapping(value = "/reactive/payment", consumes = MediaType.APPLICATION_JSON) 46 | public Mono addPayment(@RequestBody PaymentDto payment) { 47 | return postTimer.record( 48 | () -> paymentRepository.addPayments(payment) 49 | ); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/api/PropagatesExceptionEndpoint.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.api; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.PathVariable; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | import javax.ws.rs.NotFoundException; 8 | 9 | @RestController 10 | public class PropagatesExceptionEndpoint { 11 | 12 | // Not REST friendly: exception is propagated to the REST caller 13 | // That information should be internal to REST Service 14 | @GetMapping("/entity/{userId}") 15 | public String getEntity(@PathVariable final String userId) { 16 | return getByUser(userId); 17 | 18 | } 19 | 20 | private String getByUser(String userId) { 21 | // Simulate error 22 | throw new NotFoundException("Cannot get user by userId:" + userId); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/api/RESTErrorHandlingController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.api; 2 | 3 | import org.springframework.http.ResponseEntity; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import javax.ws.rs.NotFoundException; 9 | 10 | @RestController() 11 | public class RESTErrorHandlingController { 12 | 13 | 14 | @GetMapping("/entity-two/{userId}") 15 | public ResponseEntity getEntity(@PathVariable final String userId) { 16 | try { 17 | return ResponseEntity.ok(getByUser(userId)); 18 | } catch (NotFoundException ex) { 19 | return ResponseEntity.notFound().build(); //will map to proper REST error code 20 | } 21 | } 22 | 23 | private String getByUser(String userId) { 24 | // Simulate error 25 | throw new NotFoundException("Cannot get user by userId:" + userId); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/domain/Payment.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.domain; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | 8 | @Entity 9 | public class Payment { 10 | @Id 11 | @GeneratedValue(strategy = GenerationType.AUTO) 12 | private Long id; 13 | private String userId; 14 | private String accountFrom; 15 | private String accountTo; 16 | private Long amount; 17 | 18 | public Payment() { 19 | } 20 | 21 | public Payment(String userId, String accountFrom, String accountTo, Long amount) { 22 | this.userId = userId; 23 | this.accountFrom = accountFrom; 24 | this.accountTo = accountTo; 25 | this.amount = amount; 26 | } 27 | 28 | public Payment(Long id, String userId, String accountFrom, String accountTo, Long amount) { 29 | this.id = id; 30 | this.userId = userId; 31 | this.accountFrom = accountFrom; 32 | this.accountTo = accountTo; 33 | this.amount = amount; 34 | } 35 | 36 | public String getUserId() { 37 | return userId; 38 | } 39 | 40 | public String getAccountFrom() { 41 | return accountFrom; 42 | } 43 | 44 | public String getAccountTo() { 45 | return accountTo; 46 | } 47 | 48 | public Long getId() { 49 | return id; 50 | } 51 | 52 | public Long getAmount() { 53 | return amount; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "Payment{" + 59 | "id=" + id + 60 | ", userId='" + userId + '\'' + 61 | ", accountFrom='" + accountFrom + '\'' + 62 | ", accountTo='" + accountTo + '\'' + 63 | ", amount=" + amount + 64 | '}'; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/domain/PaymentAndUser.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.domain; 2 | 3 | import java.util.List; 4 | 5 | public class PaymentAndUser { 6 | private final User user; 7 | private final List payments; 8 | 9 | public PaymentAndUser(User user, List payments) { 10 | 11 | this.user = user; 12 | this.payments = payments; 13 | } 14 | 15 | public User getUser() { 16 | return user; 17 | } 18 | 19 | public List getPayments() { 20 | return payments; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | return "PaymentAndUser{" + 26 | "user=" + user + 27 | ", payments=" + payments + 28 | '}'; 29 | } 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/domain/PaymentDto.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.domain; 2 | 3 | public class PaymentDto { 4 | 5 | private String userId; 6 | private String accountFrom; 7 | private String accountTo; 8 | private Long amount; 9 | 10 | public PaymentDto() { 11 | } 12 | 13 | public PaymentDto(String userId, String accountFrom, String accountTo, Long amount) { 14 | this.userId = userId; 15 | this.accountFrom = accountFrom; 16 | this.accountTo = accountTo; 17 | this.amount = amount; 18 | } 19 | 20 | public String getUserId() { 21 | return userId; 22 | } 23 | 24 | public String getAccountFrom() { 25 | return accountFrom; 26 | } 27 | 28 | public String getAccountTo() { 29 | return accountTo; 30 | } 31 | 32 | public void setUserId(String userId) { 33 | this.userId = userId; 34 | } 35 | 36 | public void setAccountFrom(String accountFrom) { 37 | this.accountFrom = accountFrom; 38 | } 39 | 40 | public void setAccountTo(String accountTo) { 41 | this.accountTo = accountTo; 42 | } 43 | 44 | public Long getAmount() { 45 | return amount; 46 | } 47 | 48 | public void setAmount(Long amount) { 49 | this.amount = amount; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "PaymentDto{" + 55 | "userId='" + userId + '\'' + 56 | ", accountFrom='" + accountFrom + '\'' + 57 | ", accountTo='" + accountTo + '\'' + 58 | ", amount=" + amount + 59 | '}'; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.domain; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | 8 | @Entity 9 | public class User { 10 | 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.AUTO) 13 | private Long id; 14 | private String name; 15 | private String email; 16 | 17 | public User() { 18 | } 19 | 20 | public User(String name, String email) { 21 | this.name = name; 22 | this.email = email; 23 | } 24 | 25 | public User(Long id, String name, String email) { 26 | this.id = id; 27 | this.name = name; 28 | this.email = email; 29 | } 30 | 31 | public Long getId() { 32 | return id; 33 | } 34 | 35 | public void setId(Long id) { 36 | this.id = id; 37 | } 38 | 39 | public String getName() { 40 | return name; 41 | } 42 | 43 | public void setName(String name) { 44 | this.name = name; 45 | } 46 | 47 | public String getEmail() { 48 | return email; 49 | } 50 | 51 | public void setEmail(String email) { 52 | this.email = email; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return "User{" + 58 | "id='" + id + '\'' + 59 | ", name='" + name + '\'' + 60 | ", email='" + email + '\'' + 61 | '}'; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/domain/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.domain; 2 | 3 | public class UserDto { 4 | 5 | private Long id; 6 | private String name; 7 | private String email; 8 | 9 | public UserDto(Long id, String name, String email) { 10 | super(); 11 | this.id = id; 12 | this.name = name; 13 | this.email = email; 14 | } 15 | 16 | public Long getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Long id) { 21 | this.id = id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public String getEmail() { 33 | return email; 34 | } 35 | 36 | public void setEmail(String email) { 37 | this.email = email; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return "UserDto{" + 43 | "id=" + id + 44 | ", name='" + name + '\'' + 45 | ", email='" + email + '\'' + 46 | '}'; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/persistance/PaymentRepository.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.persistance; 2 | 3 | import com.tomekl007.chapter_3.domain.Payment; 4 | import org.springframework.data.jpa.repository.Query; 5 | import org.springframework.data.repository.CrudRepository; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | import java.util.List; 9 | 10 | public interface PaymentRepository extends CrudRepository { 11 | 12 | @Query("select t from Payment t where t.userId =:userId") 13 | List findByUserId(@Param("userId") String userId); 14 | 15 | @Query("select t from Payment t where t.accountFrom =:accountFrom") 16 | List findByFromAccount(@Param("accountFrom") String accountFrom); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/persistance/PaymentRestRepository.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.persistance; 2 | 3 | import com.tomekl007.chapter_3.domain.Payment; 4 | import org.springframework.data.jpa.repository.Query; 5 | import org.springframework.data.repository.PagingAndSortingRepository; 6 | import org.springframework.data.repository.query.Param; 7 | import org.springframework.data.rest.core.annotation.RepositoryRestResource; 8 | 9 | import java.util.List; 10 | 11 | @RepositoryRestResource(collectionResourceRel = "payment", path = "payment") 12 | public interface PaymentRestRepository extends PagingAndSortingRepository { 13 | 14 | @Query("select t from Payment t where t.accountTo =:accountTo") 15 | List findByAccountTo(@Param("accountTo") String accountTo); 16 | 17 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/persistance/ReactivePaymentService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.persistance; 2 | 3 | 4 | import com.tomekl007.chapter_3.domain.Payment; 5 | import com.tomekl007.chapter_3.domain.PaymentDto; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Component; 8 | import reactor.core.publisher.Mono; 9 | import reactor.core.scheduler.Schedulers; 10 | 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | 14 | @Component 15 | public class ReactivePaymentService { 16 | 17 | //note composition 18 | private final PaymentRepository paymentRepository; 19 | 20 | @Autowired 21 | public ReactivePaymentService(PaymentRepository paymentRepository) { 22 | 23 | this.paymentRepository = paymentRepository; 24 | } 25 | 26 | public Mono> getPayments(String userId) { 27 | return Mono.defer(() -> Mono.just(paymentRepository.findByUserId(userId))) 28 | .subscribeOn(Schedulers.elastic()) 29 | .map(p -> 30 | p.stream().map(p1 -> new PaymentDto(p1.getUserId(), 31 | p1.getAccountFrom(), p1.getAccountTo(), p1.getAmount())) 32 | .collect(Collectors.toList())); 33 | } 34 | 35 | public Mono addPayments(final PaymentDto payment) { 36 | return Mono.just(payment) 37 | .map(t -> new Payment(t.getUserId(), t.getAccountFrom(), t.getAccountTo(), t.getAmount())) 38 | .publishOn(Schedulers.parallel()) 39 | .doOnNext(paymentRepository::save) 40 | .map(t -> new PaymentDto(t.getUserId(), t.getAccountFrom(), t.getAccountTo(), t.getAmount())); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_3/persistance/UsersRepository.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3.persistance; 2 | 3 | import com.tomekl007.chapter_3.domain.User; 4 | import org.springframework.data.jpa.repository.Query; 5 | import org.springframework.data.repository.CrudRepository; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | import java.util.List; 9 | 10 | public interface UsersRepository extends CrudRepository { 11 | 12 | @Query("select t from User t where t.name =:name") 13 | List findByName(@Param("name") String name); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_6/FacebookService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_6; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.web.client.RestTemplate; 7 | 8 | @Component 9 | public class FacebookService { 10 | 11 | private RestTemplate restTemplate; 12 | 13 | @Autowired 14 | public FacebookService(@Qualifier("facebook-client") RestTemplate restTemplate) { 15 | 16 | this.restTemplate = restTemplate; 17 | } 18 | 19 | public void simpleGet() { 20 | restTemplate.getForEntity("http://facebook.com", String.class); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_6/PaymentDetailsWithFallback.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_6; 2 | 3 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 4 | import com.tomekl007.payment.details.api.PaymentDetails; 5 | import com.tomekl007.eventbus.api.EventBus; 6 | import com.tomekl007.eventbus.domain.Event; 7 | import org.apache.log4j.Logger; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Qualifier; 10 | import org.springframework.context.annotation.Profile; 11 | import org.springframework.metrics.instrument.MeterRegistry; 12 | import org.springframework.metrics.instrument.Timer; 13 | import org.springframework.metrics.instrument.stats.quantile.GKQuantiles; 14 | import org.springframework.scheduling.annotation.Scheduled; 15 | import org.springframework.stereotype.Component; 16 | import org.springframework.web.client.RestTemplate; 17 | 18 | import java.time.Instant; 19 | 20 | @Component 21 | @Profile("!integration") 22 | public class PaymentDetailsWithFallback implements PaymentDetails { 23 | static Logger log = Logger.getLogger(PaymentDetailsWithFallback.class.getName()); 24 | 25 | private EventBus eventBus; 26 | 27 | @Autowired 28 | private MeterRegistry meterRegistry; 29 | 30 | @Autowired 31 | public PaymentDetailsWithFallback( 32 | @Qualifier("payments-client") RestTemplate rest, 33 | EventBus eventBus) { 34 | this.eventBus = eventBus; 35 | } 36 | 37 | @HystrixCommand(fallbackMethod = "reliable") 38 | @Override 39 | public String getInfoAboutPayment(String account) { 40 | return request(account); 41 | } 42 | 43 | public String request(String account) { 44 | Timer timer = meterRegistry 45 | .timerBuilder("payment_detail_request") 46 | .quantiles(GKQuantiles.quantiles(0.99, 0.90, 0.50).create()).create(); 47 | return timer.record(() -> requestForPaymentDetails(account)); 48 | } 49 | 50 | private String requestForPaymentDetails(String account) { 51 | 52 | return "{\"name\" : " + account + ", \"time\": " + Instant.now() + "}"; 53 | } 54 | 55 | public String reliable(String account) { 56 | meterRegistry.counter("hystrix_fallback").increment(); 57 | return "Info about payment: " + account + " is not currently not available"; 58 | } 59 | 60 | @Scheduled(fixedRate = 1000) 61 | public void processEvents() { 62 | Event event = eventBus.receive(); 63 | if (event != null) { 64 | log.info("received event to process :" + event); 65 | } 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_6/RestTemplateConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_6; 2 | 3 | import org.apache.http.client.HttpClient; 4 | import org.apache.http.client.config.RequestConfig; 5 | import org.apache.http.impl.client.CloseableHttpClient; 6 | import org.apache.http.impl.client.HttpClientBuilder; 7 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 11 | import org.springframework.web.client.RestTemplate; 12 | 13 | 14 | @Configuration 15 | public class RestTemplateConfiguration { 16 | public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(int maxTotal, int maxPerRoute) { 17 | PoolingHttpClientConnectionManager result = new PoolingHttpClientConnectionManager(); 18 | result.setMaxTotal(maxTotal); 19 | result.setDefaultMaxPerRoute(maxPerRoute); 20 | return result; 21 | } 22 | 23 | public RequestConfig requestConfig(int connectionTimeout, int socketTimeout) { 24 | RequestConfig result = RequestConfig.custom() 25 | .setConnectionRequestTimeout(1000)//how long wait for a connection from connection manager 26 | .setConnectTimeout(connectionTimeout)//how long wait for establishing connection 27 | .setSocketTimeout(socketTimeout)//how long wait between packets 28 | .build(); 29 | return result; 30 | } 31 | public CloseableHttpClient httpClient(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager, RequestConfig requestConfig) { 32 | CloseableHttpClient result = HttpClientBuilder 33 | .create() 34 | .setConnectionManager(poolingHttpClientConnectionManager) 35 | .setDefaultRequestConfig(requestConfig) 36 | .build(); 37 | return result; 38 | } 39 | 40 | @Bean("payments-client") 41 | public RestTemplate restTemplateCountries() { 42 | PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = poolingHttpClientConnectionManager(20, 20); 43 | RequestConfig requestConfig = requestConfig(2000, 1400); 44 | CloseableHttpClient httpClient = httpClient(poolingHttpClientConnectionManager, requestConfig); 45 | HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); 46 | requestFactory.setHttpClient(httpClient); 47 | return new RestTemplate(requestFactory); 48 | } 49 | 50 | @Bean("facebook-client") 51 | public RestTemplate restTemplateFacebook() { 52 | PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = poolingHttpClientConnectionManager(20, 20); 53 | RequestConfig requestConfig = requestConfig(1000, 700); 54 | CloseableHttpClient httpClient = httpClient(poolingHttpClientConnectionManager, requestConfig); 55 | HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); 56 | requestFactory.setHttpClient(httpClient); 57 | return new RestTemplate(requestFactory); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_6/retry/DefaultListenerSupport.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_6.retry; 2 | 3 | import org.springframework.retry.RetryCallback; 4 | import org.springframework.retry.RetryContext; 5 | import org.springframework.retry.listener.RetryListenerSupport; 6 | 7 | public class DefaultListenerSupport extends RetryListenerSupport { 8 | @Override 9 | public void close(RetryContext context, 10 | RetryCallback callback, Throwable throwable) { 11 | System.out.println("onClose"); 12 | 13 | super.close(context, callback, throwable); 14 | } 15 | 16 | @Override 17 | public void onError(RetryContext context, 18 | RetryCallback callback, Throwable throwable) { 19 | System.out.println("onError"); 20 | super.onError(context, callback, throwable); 21 | } 22 | 23 | @Override 24 | public boolean open(RetryContext context, 25 | RetryCallback callback) { 26 | System.out.println("onOpen"); 27 | return super.open(context, callback); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/chapter_6/retry/RetryTemplateConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_6.retry; 2 | 3 | 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.retry.backoff.FixedBackOffPolicy; 7 | import org.springframework.retry.policy.SimpleRetryPolicy; 8 | import org.springframework.retry.support.RetryTemplate; 9 | 10 | @Configuration 11 | public class RetryTemplateConfiguration { 12 | 13 | @Bean 14 | public RetryTemplate retryTemplate(DefaultListenerSupport defaultListenerSupport) { 15 | RetryTemplate retryTemplate = new RetryTemplate(); 16 | retryTemplate.registerListener(defaultListenerSupport); 17 | FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); 18 | fixedBackOffPolicy.setBackOffPeriod(2000L); 19 | retryTemplate.setBackOffPolicy(fixedBackOffPolicy); 20 | 21 | SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); 22 | retryPolicy.setMaxAttempts(2); 23 | retryTemplate.setRetryPolicy(retryPolicy); 24 | 25 | 26 | return retryTemplate; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/eventbus/api/EventBus.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.eventbus.api; 2 | 3 | import com.tomekl007.eventbus.domain.Event; 4 | 5 | public interface EventBus { 6 | void publish(Event event); 7 | Event receive(); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/eventbus/domain/Event.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.eventbus.domain; 2 | 3 | import java.util.Objects; 4 | 5 | public class Event { 6 | private final String action; 7 | private final String description; 8 | 9 | public Event(String action, String description) { 10 | this.action = action; 11 | this.description = description; 12 | } 13 | 14 | @Override 15 | public boolean equals(Object o) { 16 | if (this == o) return true; 17 | if (o == null || getClass() != o.getClass()) return false; 18 | Event event = (Event) o; 19 | return Objects.equals(action, event.action) && 20 | Objects.equals(description, event.description); 21 | } 22 | 23 | @Override 24 | public int hashCode() { 25 | return Objects.hash(action, description); 26 | } 27 | 28 | 29 | @Override 30 | public String toString() { 31 | return "Event{" + 32 | "action='" + action + '\'' + 33 | ", description='" + description + '\'' + 34 | '}'; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/eventbus/infrastructure/InMemoryEventBus.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.eventbus.infrastructure; 2 | 3 | import com.tomekl007.eventbus.api.EventBus; 4 | import com.tomekl007.eventbus.domain.Event; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.util.Queue; 8 | import java.util.concurrent.LinkedBlockingDeque; 9 | 10 | @Component 11 | public class InMemoryEventBus implements EventBus { 12 | private final Queue queue = new LinkedBlockingDeque<>(); 13 | 14 | @Override 15 | public void publish(Event event) { 16 | queue.add(event); 17 | } 18 | 19 | @Override 20 | public Event receive() { 21 | return queue.poll(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/metrics/MetricsSetup.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.metrics; 2 | 3 | import io.prometheus.client.CollectorRegistry; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.metrics.instrument.Clock; 7 | import org.springframework.metrics.instrument.MeterRegistry; 8 | import org.springframework.metrics.instrument.prometheus.PrometheusMeterRegistry; 9 | 10 | //@Configuration 11 | public class MetricsSetup { 12 | @Bean 13 | public Clock micrometerClock() { 14 | return Clock.SYSTEM; 15 | } 16 | 17 | @Bean 18 | public MeterRegistry prometheusMeterRegistry(CollectorRegistry collectorRegistry, 19 | Clock clock) { 20 | return new PrometheusMeterRegistry(collectorRegistry, clock); 21 | } 22 | 23 | @Bean 24 | public CollectorRegistry collectorRegistry() { 25 | return new CollectorRegistry(true); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/metrics/MetrricsCustomController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.metrics; 2 | 3 | import org.apache.http.entity.ContentType; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.metrics.instrument.Meter; 8 | import org.springframework.metrics.instrument.MeterRegistry; 9 | import org.springframework.metrics.instrument.prometheus.PrometheusMeterRegistry; 10 | import org.springframework.stereotype.Controller; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestMethod; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import java.util.List; 16 | import java.util.function.Function; 17 | import java.util.stream.Collectors; 18 | 19 | @Controller 20 | @RequestMapping(value = "/custom/metrics") 21 | public final class MetrricsCustomController { 22 | 23 | private static final Logger LOGGER = LoggerFactory.getLogger(MetrricsCustomController.class); 24 | 25 | @Autowired 26 | private MeterRegistry registry; 27 | 28 | @RequestMapping(method = RequestMethod.GET, produces = "application/json") 29 | @ResponseBody 30 | public List getMetrics() { 31 | LOGGER.info("/metrics [GET]"); 32 | return registry 33 | .getMeters() 34 | .stream() 35 | .map((Function) 36 | Meter::measure) 37 | .collect(Collectors.toList()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/notifications/api/NotificationController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.notifications.api; 2 | 3 | import com.tomekl007.notifications.domain.HelloMessage; 4 | import com.tomekl007.notifications.domain.PaymentAddedNotification; 5 | import org.springframework.messaging.handler.annotation.MessageMapping; 6 | import org.springframework.messaging.handler.annotation.SendTo; 7 | import org.springframework.stereotype.Controller; 8 | 9 | @Controller 10 | public class NotificationController { 11 | 12 | 13 | @MessageMapping("/payment-add") 14 | @SendTo("/topic/greetings") 15 | public HelloMessage welcomeUser(PaymentAddedNotification paymentAddedNotification) throws Exception { 16 | Thread.sleep(1000); // simulated delay 17 | return new HelloMessage("Hello, " + paymentAddedNotification.getName() + "!"); 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/notifications/domain/HelloMessage.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.notifications.domain; 2 | 3 | public class HelloMessage { 4 | 5 | private String content; 6 | 7 | public HelloMessage() { 8 | } 9 | 10 | public HelloMessage(String content) { 11 | this.content = content; 12 | } 13 | 14 | public String getContent() { 15 | return content; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/notifications/domain/PaymentAddedNotification.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.notifications.domain; 2 | 3 | public class PaymentAddedNotification { 4 | private String name; 5 | 6 | public PaymentAddedNotification() { 7 | } 8 | 9 | public PaymentAddedNotification(String name) { 10 | this.name = name; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/notifications/infrastructure/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.notifications.infrastructure; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 5 | import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; 6 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 7 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 8 | 9 | @Configuration 10 | @EnableWebSocketMessageBroker 11 | public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { 12 | 13 | @Override 14 | public void configureMessageBroker(MessageBrokerRegistry config) { 15 | config.enableSimpleBroker("/topic"); 16 | config.setApplicationDestinationPrefixes("/app"); 17 | } 18 | 19 | @Override 20 | public void registerStompEndpoints(StompEndpointRegistry registry) { 21 | registry.addEndpoint("/gs-guide-websocket").withSockJS(); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/api/MVCController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.api; 2 | 3 | import com.tomekl007.chapter_3.domain.Payment; 4 | import com.tomekl007.chapter_3.domain.PaymentDto; 5 | import com.tomekl007.chapter_3.persistance.PaymentRepository; 6 | import com.tomekl007.eventbus.api.EventBus; 7 | import com.tomekl007.eventbus.domain.Event; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.ui.Model; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.ModelAttribute; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | 16 | import javax.annotation.PostConstruct; 17 | 18 | @Controller 19 | public class MVCController { 20 | 21 | @Autowired 22 | private PaymentRepository paymentRepository; 23 | 24 | @PostConstruct 25 | private void init() { 26 | paymentRepository.save(new Payment("T1", "dummyFrom", "dummyTo", 100L)); 27 | } 28 | 29 | @Autowired 30 | private EventBus eventBus; 31 | 32 | @RequestMapping("/mvc/all-payments") 33 | public String indexView(Model model) { 34 | model.addAttribute("list", paymentRepository.findAll()); 35 | return "allPayments"; 36 | } 37 | 38 | @PostMapping("/mvc/payment") 39 | public String paymentSubmit(@ModelAttribute PaymentDto paymentDto, Model model) { 40 | paymentRepository.save(new Payment(paymentDto.getUserId(), paymentDto.getAccountFrom(), paymentDto.getAccountTo(), paymentDto.getAmount())); 41 | eventBus.publish(new Event("SAVE", "Save payment" + paymentDto)); 42 | model.addAttribute("list", paymentRepository.findAll()); 43 | return "allPayments"; 44 | } 45 | 46 | @GetMapping("/mvc/createPayment") 47 | public String paymentForm(Model model) { 48 | model.addAttribute("paymentDto", new PaymentDto()); 49 | return "create"; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/api/PaymentService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.api; 2 | 3 | import com.tomekl007.chapter_3.domain.Payment; 4 | 5 | public interface PaymentService { 6 | boolean pay(Payment payment); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/api/UserService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.api; 2 | 3 | import com.tomekl007.chapter_3.domain.PaymentAndUser; 4 | import com.tomekl007.chapter_3.domain.User; 5 | 6 | import java.util.List; 7 | import java.util.Optional; 8 | 9 | 10 | public interface UserService { 11 | List getAllUsers(); 12 | void insert(User user); 13 | Optional getPaymentAndUsersForUserId(String userId); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/api/rest/UserController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.api.rest; 2 | 3 | import com.tomekl007.payment.api.UserService; 4 | import com.tomekl007.chapter_3.domain.PaymentAndUser; 5 | import com.tomekl007.chapter_3.domain.User; 6 | import com.tomekl007.chapter_3.domain.UserDto; 7 | import com.tomekl007.payment.infrastructure.exceptions.UserNotFoundException; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.web.bind.annotation.GetMapping; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import javax.annotation.PostConstruct; 17 | import java.util.List; 18 | import java.util.Optional; 19 | import java.util.stream.Collectors; 20 | 21 | 22 | @RestController 23 | @RequestMapping("/users") 24 | public class UserController { 25 | private static final Logger LOG = LoggerFactory.getLogger(UserController.class); 26 | 27 | private final UserService userService; 28 | 29 | @PostConstruct 30 | public void insertUsers() { 31 | userService.insert(new User("T1", "m@m.pl")); 32 | userService.insert(new User("T2", "m2@m.pl")); 33 | userService.insert(new User("T3", "m3@m.pl")); 34 | } 35 | 36 | @Autowired 37 | public UserController(UserService userService) { 38 | this.userService = userService; 39 | } 40 | 41 | 42 | @GetMapping(value = "", produces = "application/json") 43 | public List getAllUsers() { 44 | LOG.info("Fetching all the users"); 45 | return userService.getAllUsers().stream().map( 46 | u -> new UserDto(u.getId(), u.getName(), u.getEmail()) 47 | ).collect(Collectors.toList()); 48 | } 49 | 50 | @GetMapping(value = "payments-for-user/{userId}", produces = "application/json") 51 | public PaymentAndUser paymentAndUsers(@PathVariable final String userId) throws UserNotFoundException { 52 | Optional paymentAndUsersForUserId = userService.getPaymentAndUsersForUserId(userId); 53 | if (!paymentAndUsersForUserId.isPresent()) { 54 | throw new UserNotFoundException("Payments for user id: " + userId + " not found"); 55 | } else { 56 | return paymentAndUsersForUserId.get(); 57 | } 58 | 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/details/api/PaymentDetails.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.details.api; 2 | 3 | public interface PaymentDetails { 4 | String getInfoAboutPayment(String cityName); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/details/api/PaymentDetailsController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.details.api; 2 | 3 | 4 | import com.google.common.cache.CacheBuilder; 5 | import com.google.common.cache.CacheLoader; 6 | import com.google.common.cache.LoadingCache; 7 | import com.google.common.cache.RemovalListener; 8 | import org.apache.log4j.Logger; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.metrics.annotation.Timed; 11 | import org.springframework.metrics.instrument.MeterRegistry; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import javax.ws.rs.core.MediaType; 17 | import java.util.concurrent.TimeUnit; 18 | 19 | @RestController 20 | public class PaymentDetailsController { 21 | private static Logger log = Logger.getLogger(PaymentDetailsController.class); 22 | 23 | private PaymentDetails paymentDetails; 24 | 25 | private LoadingCache loader = 26 | CacheBuilder 27 | .newBuilder() 28 | .maximumSize(100) //on prod should be higher 29 | .expireAfterWrite(10, TimeUnit.SECONDS) 30 | .removalListener((RemovalListener) removalNotification -> { 31 | log.info("entry from cache expired: " + removalNotification); 32 | }) 33 | .build( 34 | new CacheLoader() { 35 | @Override 36 | public String load(String key) { 37 | return paymentDetails.getInfoAboutPayment(key); 38 | } 39 | }); 40 | 41 | @Autowired 42 | public PaymentDetailsController( 43 | PaymentDetails paymentDetails, 44 | MeterRegistry meterRegistry) { 45 | this.paymentDetails = paymentDetails; 46 | meterRegistry.gauge("cache_size", loader, v -> loader.size()); 47 | 48 | } 49 | 50 | @Timed 51 | @RequestMapping(value = "/payment/payment-details/{account}", produces = MediaType.APPLICATION_JSON) 52 | String getInfoAboutPayment(@PathVariable final String account) throws Exception { 53 | return loader.get(account); 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/audit/LoggingAspect.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.audit; 2 | 3 | import org.apache.log4j.Logger; 4 | import org.aspectj.lang.JoinPoint; 5 | import org.aspectj.lang.annotation.Before; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.Arrays; 9 | 10 | @Component 11 | //@Aspect 12 | public class LoggingAspect { 13 | static Logger log = Logger.getLogger(LoggingAspect.class.getName()); 14 | 15 | 16 | @Before("execution(* com.tomekl007.payment.api.PaymentService.pay(..))") 17 | public void logPaymentRequest(JoinPoint joinPoint) { 18 | log.info("before payment request with arguments: " + Arrays.toString(joinPoint.getArgs())); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/configuration/FilterConfig.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.configuration; 2 | 3 | import com.tomekl007.payment.infrastructure.filter.InterceptRequestResponseFilter; 4 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | @Configuration 9 | public class FilterConfig { 10 | 11 | 12 | @Bean 13 | public FilterRegistrationBean loggingFilter() { 14 | FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); 15 | 16 | registrationBean.setFilter(new InterceptRequestResponseFilter()); 17 | 18 | registrationBean.addUrlPatterns("/users/*"); 19 | 20 | return registrationBean; 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/configuration/PaymentServiceSettings.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.configuration; 2 | 3 | 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.util.List; 8 | 9 | @Component 10 | @ConfigurationProperties(prefix = "payment-config") 11 | public class PaymentServiceSettings { 12 | 13 | private List supportedAccounts; 14 | 15 | public List getSupportedAccounts() { 16 | return supportedAccounts; 17 | } 18 | 19 | public void setSupportedAccounts(List supportedAccounts) { 20 | this.supportedAccounts = supportedAccounts; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/exceptions/UserNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.exceptions; 2 | 3 | public class UserNotFoundException extends Throwable { 4 | public UserNotFoundException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/filter/InterceptRequestResponseFilter.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.filter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.core.annotation.Order; 17 | import org.springframework.stereotype.Component; 18 | 19 | public class InterceptRequestResponseFilter implements Filter { 20 | 21 | private final static Logger LOG = LoggerFactory.getLogger(InterceptRequestResponseFilter.class); 22 | 23 | @Override 24 | public void init(final FilterConfig filterConfig) { 25 | LOG.info("Initializing filter :{}", this); 26 | } 27 | 28 | @Override 29 | public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) 30 | throws IOException, ServletException { 31 | HttpServletRequest req = (HttpServletRequest) request; 32 | HttpServletResponse res = (HttpServletResponse) response; 33 | logInfoAboutRequestAndResponse(request, response, chain, req, res); 34 | 35 | } 36 | 37 | private void logInfoAboutRequestAndResponse(ServletRequest request, ServletResponse response, FilterChain chain, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { 38 | LOG.info("Logging Request {} : {}", req.getMethod(), req.getRequestURI()); 39 | chain.doFilter(request, response); 40 | LOG.info("Logging Response :{}", res.getContentType()); 41 | } 42 | 43 | @Override 44 | public void destroy() { 45 | LOG.warn("Destructing filter :{}", this); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/filter/TransactionFilter.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.filter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | import com.tomekl007.payment.service.TransactionService; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.core.annotation.Order; 18 | import org.springframework.stereotype.Component; 19 | 20 | 21 | 22 | public class TransactionFilter implements Filter { 23 | 24 | private final static Logger LOG = LoggerFactory.getLogger(TransactionFilter.class); 25 | 26 | @Autowired 27 | private TransactionService transactionService; 28 | 29 | @Override 30 | public void init(final FilterConfig filterConfig) { 31 | LOG.info("Initializing filter :{}", this); 32 | } 33 | 34 | @Override 35 | public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { 36 | HttpServletRequest req = (HttpServletRequest) request; 37 | transactionService.startTransaction(req); 38 | chain.doFilter(request, response); 39 | transactionService.commitTransaction(req); 40 | 41 | } 42 | 43 | @Override 44 | public void destroy() { 45 | LOG.warn("Destructing filter :{}", this); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/healtchecks/DownstreamHealthcheck.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.healtchecks; 2 | 3 | import com.tomekl007.payment.details.api.PaymentDetails; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.actuate.health.Health; 6 | import org.springframework.boot.actuate.health.HealthIndicator; 7 | import org.springframework.stereotype.Component; 8 | 9 | @Component 10 | public class DownstreamHealthcheck implements HealthIndicator { 11 | 12 | @Autowired 13 | private PaymentDetails paymentDetails; 14 | 15 | @Override 16 | public Health health() { 17 | try { 18 | //try some non existing 19 | String response = paymentDetails.getInfoAboutPayment("INIT-COMPANY"); 20 | if (response.contains("is not currently not available")) { 21 | return Health.down().build(); 22 | } 23 | return Health.up().build(); 24 | } catch (Exception ex) { 25 | return Health.down(ex).build(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/security/SecretController.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.security; 2 | 3 | import com.tomekl007.chapter_3.persistance.PaymentRepository; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | public class SecretController { 10 | 11 | @Autowired 12 | private PaymentRepository paymentRepository; 13 | 14 | @RequestMapping("/secret") 15 | public Long numberOfPayment() { 16 | return paymentRepository.count(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/security/SpringSecurityWebAppConfig.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.security; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.http.HttpMethod; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9 | 10 | 11 | @EnableWebSecurity 12 | @Configuration 13 | public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter { 14 | @Override 15 | protected void configure(HttpSecurity http) throws Exception { 16 | http.authorizeRequests() 17 | .antMatchers(HttpMethod.GET, "/reactive/**", "/mvc/**", "/payment-add", "/topic", "/application/**") 18 | .permitAll() 19 | .and() 20 | .authorizeRequests() 21 | .antMatchers(HttpMethod.POST, "/reactive/**", "/mvc/**", "/payment-add", "/topic") 22 | .permitAll() 23 | .and() 24 | .csrf() 25 | .disable() 26 | .cors() 27 | .disable() 28 | .authorizeRequests() 29 | .antMatchers(HttpMethod.GET, "/secret") 30 | .denyAll(); 31 | 32 | } 33 | 34 | @Override 35 | public void configure(WebSecurity web) throws Exception { 36 | web.ignoring().antMatchers("/templates/**", "/assets/**"); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/infrastructure/security/SpringSecurityWebAppConfigWithCsrf.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.infrastructure.security; 2 | 3 | import org.springframework.http.HttpMethod; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 | 8 | public class SpringSecurityWebAppConfigWithCsrf extends WebSecurityConfigurerAdapter { 9 | @Override 10 | protected void configure(HttpSecurity http) throws Exception { 11 | http.authorizeRequests() 12 | .antMatchers(HttpMethod.GET, "/reactive/**", "/mvc/**", "/payment-add", "/topic") 13 | .permitAll() 14 | .and() 15 | .authorizeRequests() 16 | .antMatchers(HttpMethod.POST, "/reactive/**", "/mvc/**", "/payment-add", "/topic") 17 | .permitAll() 18 | .and() 19 | .authorizeRequests() 20 | .antMatchers(HttpMethod.GET, "/secret") 21 | .denyAll(); 22 | 23 | } 24 | 25 | @Override 26 | public void configure(WebSecurity web) throws Exception { 27 | web.ignoring().antMatchers("/templates/**", "/assets/**"); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/service/ExternalPaymentService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.service; 2 | 3 | import com.tomekl007.payment.api.PaymentService; 4 | import com.tomekl007.chapter_3.domain.Payment; 5 | import com.tomekl007.payment.infrastructure.configuration.PaymentServiceSettings; 6 | import com.tomekl007.chapter_3.persistance.PaymentRepository; 7 | import com.tomekl007.eventbus.api.EventBus; 8 | import com.tomekl007.eventbus.domain.Event; 9 | import org.apache.log4j.Logger; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.metrics.instrument.MeterRegistry; 12 | import org.springframework.stereotype.Component; 13 | 14 | import javax.annotation.PostConstruct; 15 | import javax.annotation.PreDestroy; 16 | 17 | @Component 18 | public class ExternalPaymentService implements PaymentService { 19 | static Logger log = Logger.getLogger(ExternalPaymentService.class.getName()); 20 | 21 | @Autowired 22 | MeterRegistry meterRegistry; 23 | 24 | private final PaymentServiceSettings paymentServiceSettings; 25 | private final PaymentRepository paymentRepository; 26 | private EventBus eventBus; 27 | 28 | @Autowired 29 | public ExternalPaymentService(PaymentServiceSettings paymentServiceSettings, 30 | PaymentRepository paymentRepository, 31 | EventBus eventBus) { 32 | this.paymentServiceSettings = paymentServiceSettings; 33 | this.paymentRepository = paymentRepository; 34 | this.eventBus = eventBus; 35 | } 36 | 37 | @Override 38 | public boolean pay(Payment payment) { 39 | if (paymentServiceSettings.getSupportedAccounts().contains(payment.getAccountTo())) { 40 | paymentRepository.save(payment); 41 | eventBus.publish(new Event("SAVED", "Saved payment " + payment)); 42 | return true; 43 | } 44 | eventBus.publish(new Event("REJECTED", "Rejected payment " + payment)); 45 | return false; 46 | } 47 | 48 | @PostConstruct 49 | public void init() { 50 | log.info("in init method"); 51 | } 52 | 53 | @PreDestroy 54 | public void cleanup() { 55 | log.info("in cleanup method. Possible to release some resources"); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/service/TransactionService.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.service; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | public class TransactionService { 10 | private final static Logger LOG = LoggerFactory.getLogger(TransactionService.class); 11 | 12 | 13 | public void startTransaction(HttpServletRequest req) { 14 | LOG.info("Starting Transaction for req :{}", req.getRequestURI()); 15 | } 16 | 17 | public void commitTransaction(HttpServletRequest req) { 18 | LOG.info("Committing Transaction for req :{}", req.getRequestURI()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/tomekl007/payment/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.payment.service; 2 | 3 | import com.tomekl007.payment.api.UserService; 4 | import com.tomekl007.chapter_3.domain.Payment; 5 | import com.tomekl007.chapter_3.domain.PaymentAndUser; 6 | import com.tomekl007.chapter_3.domain.User; 7 | import com.tomekl007.chapter_3.persistance.PaymentRepository; 8 | import com.tomekl007.chapter_3.persistance.UsersRepository; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.util.List; 13 | import java.util.Optional; 14 | import java.util.stream.Collectors; 15 | import java.util.stream.StreamSupport; 16 | 17 | @Component 18 | public class UserServiceImpl implements UserService { 19 | 20 | @Autowired 21 | private UsersRepository usersRepository; 22 | 23 | @Autowired 24 | private PaymentRepository paymentRepository; 25 | 26 | @Override 27 | public List getAllUsers() { 28 | return StreamSupport.stream(usersRepository.findAll().spliterator(), false) 29 | .collect(Collectors.toList()); 30 | } 31 | 32 | @Override 33 | public void insert(User user) { 34 | usersRepository.save(user); 35 | } 36 | 37 | @Override 38 | public Optional getPaymentAndUsersForUserId(String userId) { 39 | List users = usersRepository.findByName(userId); 40 | List payments = paymentRepository.findByUserId(userId); 41 | if(users.isEmpty()){ 42 | return Optional.empty(); 43 | } 44 | return Optional.of(new PaymentAndUser(users.get(0), payments)); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | service-config: 2 | b: "This-is-application-dev.yml config" -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | payment-config.supportedAccounts: accoutFirst, accountSecond, accountThird, accountFourth 2 | 3 | management.endpoints.web.base-path: "/" 4 | management.endpoints.web.exposure.include: "*" 5 | management.health.defaults.enabled: true 6 | 7 | 8 | management: 9 | endpoints: 10 | web: 11 | exposure: 12 | include: info, health, metrics 13 | metrics: 14 | export: 15 | atlas: 16 | enabled: false 17 | security: 18 | enabled: false 19 | 20 | service-config: 21 | a: 1 22 | b: "This-is-application.yml config" -------------------------------------------------------------------------------- /src/main/resources/docker_build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | mvn clean package docker:build -DskipTests 3 | docker images --all 4 | docker run hands-on-spring-packt-docker-image 5 | docker ps 6 | docker exec -it 23f049b57f9f curl http://localhost:8080/application/health -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Set root logger level to DEBUG and its only appender to A1. 2 | log4j.rootLogger=DEBUG, A1 3 | 4 | # A1 is set to be a ConsoleAppender. 5 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 6 | 7 | # A1 uses PatternLayout. 8 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout 9 | log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -------------------------------------------------------------------------------- /src/main/resources/static/app.js: -------------------------------------------------------------------------------- 1 | var stompClient = null; 2 | 3 | function setConnected(connected) { 4 | $("#connect").prop("disabled", connected); 5 | $("#disconnect").prop("disabled", !connected); 6 | if (connected) { 7 | $("#conversation").show(); 8 | } 9 | else { 10 | $("#conversation").hide(); 11 | } 12 | $("#greetings").html(""); 13 | } 14 | 15 | function connect() { 16 | var socket = new SockJS('/gs-guide-websocket'); 17 | stompClient = Stomp.over(socket); 18 | stompClient.connect({}, function (frame) { 19 | setConnected(true); 20 | console.log('Connected: ' + frame); 21 | stompClient.subscribe('/topic/greetings', function (greeting) { 22 | showGreeting(JSON.parse(greeting.body).content); 23 | }); 24 | }); 25 | } 26 | 27 | function disconnect() { 28 | if (stompClient != null) { 29 | stompClient.disconnect(); 30 | } 31 | setConnected(false); 32 | console.log("Disconnected"); 33 | } 34 | 35 | function sendName() { 36 | stompClient.send("/app/payment-add", {}, JSON.stringify({'name': $("#name").val()})); 37 | } 38 | 39 | function showGreeting(message) { 40 | $("#greetings").append("" + message + ""); 41 | } 42 | 43 | $(function () { 44 | $("form").on('submit', function (e) { 45 | e.preventDefault(); 46 | }); 47 | $( "#connect" ).click(function() { connect(); }); 48 | $( "#disconnect" ).click(function() { disconnect(); }); 49 | $( "#send" ).click(function() { sendName(); }); 50 | }); -------------------------------------------------------------------------------- /src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hello WebSocket 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 |
17 |
18 |
19 |
20 |
21 | 22 | 23 | 25 |
26 |
27 |
28 |
29 |
30 |
31 | 32 | 33 |
34 | 35 |
36 |
37 |
38 |
39 |
40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 |
Greetings
49 |
50 |
51 | 52 |
53 | 54 | -------------------------------------------------------------------------------- /src/main/resources/static/main.css: -------------------------------------------------------------------------------- 1 | 2 | body { 3 | background-color: #f5f5f5; 4 | } 5 | 6 | #main-content { 7 | max-width: 940px; 8 | padding: 2em 3em; 9 | margin: 0 auto 20px; 10 | background-color: #fff; 11 | border: 1px solid #e5e5e5; 12 | -webkit-border-radius: 5px; 13 | -moz-border-radius: 5px; 14 | border-radius: 5px; 15 | } -------------------------------------------------------------------------------- /src/main/resources/status_endoints.sh: -------------------------------------------------------------------------------- 1 | http://localhost:8080/application/info 2 | http://localhost:8080/application/health 3 | 4 | 5 | http://localhost:8080/application 6 | http://localhost:8080/application/metrics -------------------------------------------------------------------------------- /src/main/resources/templates/allPayments.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | All registered payments: 5 |
6 | 7 | userId: 8 | 9 | From Account: 10 | 11 | To Account: 12 | 13 | Amount: 14 | 15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/templates/create.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Create new Payment 4 | 5 | 6 | 7 |

Form

8 |
9 |

userId:

10 |

accountFrom:

11 |

accountTo:

12 |

amount:

13 |

14 |
15 | 16 | -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/PaymentDetailsMock.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007; 2 | 3 | 4 | import com.tomekl007.payment.details.api.PaymentDetails; 5 | import org.springframework.context.annotation.Profile; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.LinkedHashMap; 9 | import java.util.Map; 10 | 11 | @Component 12 | @Profile("integration") 13 | public class PaymentDetailsMock implements PaymentDetails { 14 | private final Map info = new LinkedHashMap<>(); 15 | 16 | public void addInfo(String key, String value){ 17 | info.put(key, value); 18 | } 19 | 20 | @Override 21 | public String getInfoAboutPayment(String cityName) { 22 | return info.get(cityName); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_3/PaymentRepositoryIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_3; 2 | 3 | import com.tomekl007.chapter_3.domain.Payment; 4 | import com.tomekl007.chapter_3.persistance.PaymentRepository; 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.context.ActiveProfiles; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import java.util.UUID; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | 18 | 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest 21 | @ActiveProfiles("integration") 22 | public class PaymentRepositoryIntegrationTest { 23 | 24 | @Autowired 25 | private PaymentRepository paymentRepository; 26 | 27 | @Test 28 | public void shouldSavePaymentAndRetrieveItByUserId() { 29 | //given 30 | String userId = "joseph"; 31 | Payment payment = new Payment(userId, "124215", "t5356315", 23L); 32 | 33 | //when 34 | paymentRepository.save(payment); 35 | List payments = paymentRepository.findByUserId(userId); 36 | 37 | //then 38 | assertThat(payments.get(0).getAccountFrom()).isEqualTo("124215"); 39 | assertThat(payments.get(0).getAccountTo()).isEqualTo("t5356315"); 40 | } 41 | 42 | @Test 43 | public void shouldRetrieveAllPaymentsThatHave123AsAccountFrom() { 44 | //given 45 | List payments = Arrays.asList( 46 | new Payment(UUID.randomUUID().toString(), "123", "55555", 23L), 47 | new Payment(UUID.randomUUID().toString(), "123", "77777", 23L), 48 | new Payment(UUID.randomUUID().toString(), "77777", "2145", 23L) 49 | ); 50 | 51 | //when 52 | paymentRepository.saveAll(payments); 53 | List foundPayments = paymentRepository.findByFromAccount("123"); 54 | 55 | //then 56 | assertThat(foundPayments.size()).isEqualTo(2); 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_5/MVCControllerSecurityTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_5; 2 | 3 | import com.tomekl007.eventbus.api.EventBus; 4 | import com.tomekl007.PaymentApplication; 5 | import com.tomekl007.payment.api.MVCController; 6 | import com.tomekl007.chapter_3.domain.Payment; 7 | import com.tomekl007.chapter_3.domain.PaymentDto; 8 | import com.tomekl007.chapter_3.persistance.PaymentRepository; 9 | import com.tomekl007.payment.infrastructure.security.SpringSecurityWebAppConfigWithCsrf; 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.autoconfigure.web.servlet.AutoConfigureMockMvc; 14 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 15 | import org.springframework.boot.test.mock.mockito.MockBean; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.test.context.ContextConfiguration; 18 | import org.springframework.test.context.junit4.SpringRunner; 19 | import org.springframework.test.web.servlet.MockMvc; 20 | 21 | import java.util.Arrays; 22 | 23 | import static org.hamcrest.core.StringContains.containsString; 24 | import static org.mockito.Mockito.when; 25 | import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; 26 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 27 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 28 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 29 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 30 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 31 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 32 | 33 | @RunWith(SpringRunner.class) 34 | @AutoConfigureMockMvc 35 | @ContextConfiguration(classes = {PaymentApplication.class, SpringSecurityWebAppConfigWithCsrf.class}) 36 | @WebMvcTest( 37 | controllers = MVCController.class 38 | ) 39 | public class MVCControllerSecurityTest { 40 | 41 | @MockBean 42 | private PaymentRepository paymentRepository; 43 | 44 | @MockBean 45 | private EventBus eventBus; 46 | 47 | @Autowired 48 | private MockMvc mockMvc; 49 | 50 | @Test 51 | public void shouldReturnAllAvailablePayments() throws Exception { 52 | //given 53 | Iterable payments = Arrays.asList( 54 | new Payment("u1", "134", 55 | "5125", 23L)); 56 | when(paymentRepository.findAll()).thenReturn(payments); 57 | 58 | //when, then 59 | this.mockMvc.perform(get("/mvc/all-payments")).andDo(print()) 60 | .andExpect(status().isOk()) 61 | .andExpect(content().string(containsString("u1"))) 62 | .andExpect(content().string(containsString("134"))) 63 | .andExpect(content().string(containsString("5125"))) 64 | .andReturn(); 65 | } 66 | 67 | @Test 68 | public void shouldReturnFormForCreatingPaymentWithCsrfHiddenField() throws Exception { 69 | //when, then 70 | this.mockMvc.perform(get("/mvc/createPayment")) 71 | .andDo(print()) 72 | .andExpect(status().isOk()) 73 | .andExpect(content().string(containsString("_csrf"))) //included! 74 | .andReturn(); 75 | } 76 | 77 | @Test 78 | public void shouldPostNewPaymentWithCsrf() throws Exception { 79 | //given 80 | PaymentDto paymentDto = new PaymentDto(); 81 | paymentDto.setUserId("u_id1"); 82 | paymentDto.setAccountFrom("123"); 83 | paymentDto.setAccountTo("5325"); 84 | 85 | mockMvc.perform( 86 | post("/mvc/payment") 87 | .contentType(MediaType.APPLICATION_FORM_URLENCODED) 88 | .with(csrf()) 89 | .sessionAttr("paymentDto", paymentDto) 90 | ) 91 | .andExpect(status().isOk()) 92 | .andExpect(view().name("allPayments")); 93 | } 94 | 95 | @Test 96 | public void shouldReturn403IfPostWithoutCsrf() throws Exception { 97 | //given 98 | PaymentDto paymentDto = new PaymentDto(); 99 | paymentDto.setUserId("u_id1"); 100 | paymentDto.setAccountFrom("4214"); 101 | paymentDto.setAccountTo("531251"); 102 | 103 | mockMvc.perform( 104 | post("/mvc/payment") 105 | .contentType(MediaType.APPLICATION_FORM_URLENCODED) 106 | //note that req send without 107 | .sessionAttr("paymentDto", paymentDto) 108 | ) 109 | .andExpect(status().is(403)); 110 | } 111 | } -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_5/MVCControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_5; 2 | 3 | import com.tomekl007.eventbus.api.EventBus; 4 | import com.tomekl007.PaymentApplication; 5 | import com.tomekl007.chapter_3.domain.Payment; 6 | import com.tomekl007.chapter_3.domain.PaymentDto; 7 | import com.tomekl007.chapter_3.persistance.PaymentRepository; 8 | import com.tomekl007.payment.api.MVCController; 9 | import com.tomekl007.payment.infrastructure.security.SpringSecurityWebAppConfig; 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.autoconfigure.web.servlet.AutoConfigureMockMvc; 14 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 15 | import org.springframework.boot.test.mock.mockito.MockBean; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.test.context.ContextConfiguration; 18 | import org.springframework.test.context.junit4.SpringRunner; 19 | import org.springframework.test.web.servlet.MockMvc; 20 | 21 | import java.util.Arrays; 22 | 23 | import static org.hamcrest.Matchers.hasProperty; 24 | import static org.hamcrest.core.IsNull.nullValue; 25 | import static org.hamcrest.core.StringContains.containsString; 26 | import static org.mockito.Mockito.when; 27 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 28 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 29 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 30 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 31 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 32 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 33 | 34 | @RunWith(SpringRunner.class) 35 | @AutoConfigureMockMvc 36 | @ContextConfiguration(classes = {PaymentApplication.class, SpringSecurityWebAppConfig.class}) 37 | @WebMvcTest( 38 | controllers = MVCController.class 39 | ) 40 | public class MVCControllerTest { 41 | 42 | @MockBean 43 | private PaymentRepository paymentRepository; 44 | 45 | @MockBean 46 | private EventBus eventBus; 47 | 48 | @Autowired 49 | private MockMvc mockMvc; 50 | 51 | @Test 52 | public void shouldReturnAllPayments() throws Exception { 53 | //given 54 | Iterable payments = Arrays.asList( 55 | new Payment("u1", "from1", 56 | "to1", 23L)); 57 | when(paymentRepository.findAll()).thenReturn(payments); 58 | 59 | //when, then 60 | this.mockMvc.perform(get("/mvc/all-payments")).andDo(print()) 61 | .andExpect(status().isOk()) 62 | .andExpect(content().string(containsString("u1"))) 63 | .andExpect(content().string(containsString("from1"))) 64 | .andExpect(content().string(containsString("to1"))) 65 | .andReturn(); 66 | } 67 | 68 | @Test 69 | public void shouldReturnFormForCreatingPayment() throws Exception { 70 | //when, then 71 | this.mockMvc.perform(get("/mvc/createPayment")).andDo(print()) 72 | .andExpect(status().isOk()) 73 | .andExpect(content().string(containsString( 74 | "
\n" + 75 | "

userId:

\n" + 76 | "

accountFrom:

\n" + 77 | "

accountTo:

\n" + 78 | "

amount:

\n" + 79 | "

\n" + 80 | "
"))) 81 | 82 | .andReturn(); 83 | } 84 | 85 | @Test 86 | public void shouldPostNewPayment() throws Exception { 87 | //given 88 | PaymentDto paymentDto = new PaymentDto(); 89 | paymentDto.setUserId("u_id1"); 90 | paymentDto.setAccountFrom("51351"); 91 | paymentDto.setAccountTo("123"); 92 | 93 | mockMvc.perform( 94 | post("/mvc/payment") 95 | .contentType(MediaType.APPLICATION_FORM_URLENCODED) 96 | .sessionAttr("paymentDto", paymentDto) 97 | ) 98 | .andExpect(status().isOk()) 99 | .andExpect(view().name("allPayments")); 100 | } 101 | } -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_5/ReactivePaymentServiceIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_5; 2 | 3 | import com.tomekl007.chapter_3.domain.PaymentDto; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.boot.test.web.client.TestRestTemplate; 10 | import org.springframework.boot.web.server.LocalServerPort; 11 | import org.springframework.core.ParameterizedTypeReference; 12 | import org.springframework.core.env.Environment; 13 | import org.springframework.http.HttpEntity; 14 | import org.springframework.http.HttpHeaders; 15 | import org.springframework.http.HttpMethod; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.http.ResponseEntity; 18 | import org.springframework.test.context.ActiveProfiles; 19 | import org.springframework.test.context.junit4.SpringRunner; 20 | import org.springframework.web.client.RestTemplate; 21 | 22 | import java.util.List; 23 | import java.util.UUID; 24 | 25 | import static org.assertj.core.api.Assertions.assertThat; 26 | 27 | 28 | @RunWith(SpringRunner.class) 29 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 30 | @ActiveProfiles("integration") 31 | public class ReactivePaymentServiceIntegrationTest { 32 | 33 | // Inject which port we was assigned 34 | @Value("${local.server.port}") 35 | private int port; 36 | 37 | 38 | @Test 39 | public void shouldCreateAndRetrievePayment() { 40 | //given 41 | RestTemplate restTemplate = new RestTemplate(); 42 | PaymentDto paymentDto = new PaymentDto(UUID.randomUUID().toString(), 43 | "123", "456", 200L); 44 | HttpHeaders httpHeaders = new HttpHeaders(); 45 | httpHeaders.setContentType(MediaType.APPLICATION_JSON); 46 | HttpEntity entity = new HttpEntity<>(paymentDto, httpHeaders); 47 | 48 | //when 49 | ResponseEntity response = restTemplate 50 | .postForEntity(createTestUrl("/reactive/payment"), 51 | entity, PaymentDto.class); 52 | 53 | //then 54 | assertThat(response.getStatusCode().value()).isEqualTo(200); 55 | assertThat(response.getBody()).isNotNull(); 56 | 57 | //when 58 | List getResponse = restTemplate.exchange( 59 | createTestUrl("/reactive/payment/" + 60 | response.getBody().getUserId()), 61 | HttpMethod.GET, 62 | null, 63 | new ParameterizedTypeReference>() { 64 | }).getBody(); 65 | 66 | //then 67 | assertThat(response.getStatusCode().value()).isEqualTo(200); 68 | assertThat(getResponse.size()).isGreaterThan(0); 69 | 70 | } 71 | 72 | private String createTestUrl(String suffix) { 73 | return "http://localhost:" + port + suffix; 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_5/ReactivePaymentServiceLiveTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_5; 2 | 3 | import com.tomekl007.chapter_3.domain.PaymentDto; 4 | import org.junit.Ignore; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.core.ParameterizedTypeReference; 9 | import org.springframework.http.*; 10 | import org.springframework.test.context.ActiveProfiles; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | import org.springframework.web.client.RestTemplate; 13 | 14 | import java.util.List; 15 | import java.util.UUID; 16 | 17 | import static org.assertj.core.api.Assertions.assertThat; 18 | 19 | 20 | @RunWith(SpringRunner.class) 21 | @SpringBootTest 22 | @ActiveProfiles("integration") 23 | public class ReactivePaymentServiceLiveTest { 24 | 25 | @Ignore 26 | @Test 27 | public void shouldCreateAndRetrievePayment() { 28 | //given 29 | RestTemplate restTemplate = new RestTemplate(); 30 | PaymentDto paymentDto = new PaymentDto(UUID.randomUUID().toString(), 31 | "123", "456", 200L); 32 | HttpHeaders httpHeaders = new HttpHeaders(); 33 | httpHeaders.setContentType(MediaType.APPLICATION_JSON); 34 | HttpEntity entity = new HttpEntity<>(paymentDto, httpHeaders); 35 | 36 | //when 37 | ResponseEntity response = restTemplate 38 | .postForEntity("http://localhost:8080/reactive/payment", 39 | entity, PaymentDto.class); 40 | 41 | //then 42 | assertThat(response.getStatusCode().value()).isEqualTo(200); 43 | assertThat(response.getBody()).isNotNull(); 44 | 45 | //when 46 | List getResponse = restTemplate.exchange( 47 | "http://localhost:8080/reactive/payment/" + 48 | response.getBody().getUserId(), 49 | HttpMethod.GET, 50 | null, 51 | new ParameterizedTypeReference>() { 52 | }).getBody(); 53 | 54 | //then 55 | assertThat(response.getStatusCode().value()).isEqualTo(200); 56 | assertThat(getResponse.size()).isGreaterThan(0); 57 | 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_6/SpringRetryTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_6; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.retry.RetryCallback; 8 | import org.springframework.retry.support.RetryTemplate; 9 | import org.springframework.test.context.ActiveProfiles; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import java.util.concurrent.atomic.AtomicInteger; 13 | 14 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 15 | 16 | @RunWith(SpringRunner.class) 17 | @SpringBootTest 18 | @ActiveProfiles("integration") 19 | public class SpringRetryTest { 20 | 21 | @Autowired 22 | private RetryTemplate retryTemplate; 23 | 24 | @Test 25 | public void givenRetryTemplate_whenRetryOnce_thenShouldSucceedOnRetry() throws Throwable { 26 | AtomicInteger atomicInteger = new AtomicInteger(0); 27 | 28 | String result = retryTemplate.execute((RetryCallback) retryContext -> { 29 | System.out.println("run number: " + atomicInteger.get()); 30 | if (atomicInteger.getAndIncrement() == 0) { 31 | throw new RuntimeException("error while first query"); 32 | } else { 33 | return "success"; 34 | } 35 | }); 36 | 37 | assertThat(result).isEqualTo("success"); 38 | } 39 | 40 | @Test(expected = RuntimeException.class) 41 | public void givenRetryTemplate_whenRetryOnceAndFailure_thenShouldPropagateError() throws Throwable { 42 | AtomicInteger atomicInteger = new AtomicInteger(0); 43 | 44 | String result = retryTemplate.execute((RetryCallback) retryContext -> { 45 | System.out.println("run number: " + atomicInteger.getAndIncrement()); 46 | 47 | throw new RuntimeException("error while query"); 48 | 49 | }); 50 | 51 | } 52 | } -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_7/MicroMeterCacheSize.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_7; 2 | 3 | import com.google.common.cache.CacheBuilder; 4 | import com.google.common.cache.CacheLoader; 5 | import com.google.common.cache.LoadingCache; 6 | import org.junit.Test; 7 | import org.springframework.metrics.instrument.Measurement; 8 | import org.springframework.metrics.instrument.Meter; 9 | import org.springframework.metrics.instrument.simple.SimpleMeterRegistry; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.Optional; 14 | import java.util.concurrent.ExecutionException; 15 | 16 | import static org.assertj.core.api.Java6Assertions.assertThat; 17 | 18 | public class MicroMeterCacheSize { 19 | private SimpleMeterRegistry metricRegistry = new SimpleMeterRegistry(); 20 | 21 | private LoadingCache cache = 22 | CacheBuilder 23 | .newBuilder() 24 | .maximumSize(10) 25 | .build( 26 | new CacheLoader() { 27 | @Override 28 | public String load(String key) { 29 | return key.toUpperCase(); 30 | } 31 | }); 32 | 33 | @Test 34 | public void shouldUseGauge() throws ExecutionException { 35 | //given 36 | metricRegistry.gauge("cache.size", cache, value -> cache.size()); 37 | 38 | //when 39 | cache.get("k"); 40 | cache.get("k2"); 41 | cache.get("k3"); 42 | 43 | //then 44 | Optional gauge = metricRegistry.findMeter( 45 | Meter.Type.Gauge, "cache.size"); 46 | List measurements = new ArrayList<>(); 47 | gauge.get().measure().iterator().forEachRemaining(measurements::add); 48 | assertThat(measurements.get(0).getValue()).isEqualTo(3.0); 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/com/tomekl007/chapter_7/ResponseTimesHistogramTest.java: -------------------------------------------------------------------------------- 1 | package com.tomekl007.chapter_7; 2 | 3 | import org.junit.Test; 4 | import org.springframework.metrics.instrument.DistributionSummary; 5 | import org.springframework.metrics.instrument.Measurement; 6 | import org.springframework.metrics.instrument.Meter; 7 | import org.springframework.metrics.instrument.MeterRegistry; 8 | import org.springframework.metrics.instrument.prometheus.PrometheusMeterRegistry; 9 | import org.springframework.metrics.instrument.simple.SimpleMeterRegistry; 10 | import org.springframework.metrics.instrument.stats.hist.NormalHistogram; 11 | import org.springframework.metrics.instrument.stats.quantile.WindowSketchQuantiles; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.stream.Collectors; 16 | 17 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 18 | 19 | public class ResponseTimesHistogramTest { 20 | public static final int NORMAL_SIZE = 20; 21 | public static final int OUTLIER_SIZE = 100; 22 | 23 | @Test 24 | public void shouldMeasureActionsBuildingHistogram() { 25 | //given 26 | SimpleMeterRegistry metricRegistry = new SimpleMeterRegistry(); 27 | DistributionSummary distributionSummary = metricRegistry 28 | .summaryBuilder("request-simple.size") 29 | .create(); 30 | 31 | //when 32 | for (int i = 0; i < 100; i++) { 33 | distributionSummary.record(NORMAL_SIZE); 34 | } 35 | //one outlier 36 | distributionSummary.record(OUTLIER_SIZE); 37 | 38 | 39 | //then 40 | 41 | assertThat(distributionSummary.count()).isEqualTo(101); 42 | assertThat(distributionSummary.totalAmount()).isEqualTo(2100); 43 | } 44 | 45 | @Test 46 | public void shouldMeasureActionsBuildingHistogramWithPercentiles() { 47 | //given 48 | MeterRegistry metricRegistry = new PrometheusMeterRegistry(); 49 | DistributionSummary distributionSummary = metricRegistry 50 | .summaryBuilder("request-percentiles.size") 51 | .quantiles( 52 | WindowSketchQuantiles 53 | .quantiles(0.3, 0.5, 0.99) 54 | .create() 55 | ) 56 | .create(); 57 | 58 | //when 59 | for (int i = 0; i < 100; i++) { 60 | distributionSummary.record(NORMAL_SIZE); 61 | } 62 | //one outlier 63 | distributionSummary.record(OUTLIER_SIZE); 64 | 65 | 66 | //then 67 | List measurements = new ArrayList<>(); 68 | metricRegistry.findMeter(Meter.Type.DistributionSummary, 69 | "request-percentiles.size") 70 | .get().measure().iterator().forEachRemaining(measurements::add); 71 | 72 | List result = 73 | extractPercentilesAsMap(measurements,"request-percentiles.size"); 74 | assertThat(result) 75 | .contains("0.3=20.0", "0.5=20.0", "0.99=100.0"); 76 | 77 | } 78 | 79 | @Test 80 | public void shouldMeasureActionsBuildingHistogramWithLinear() { 81 | //given 82 | MeterRegistry metricRegistry = new PrometheusMeterRegistry(); 83 | DistributionSummary distributionSummary = metricRegistry 84 | .summaryBuilder("request-summary.size") 85 | .histogram( 86 | new NormalHistogram(NormalHistogram 87 | .linear(0, 10, 5)) 88 | ) 89 | .create(); 90 | 91 | //when 92 | distributionSummary.record(1); 93 | distributionSummary.record(2); 94 | for (int i = 0; i < 100; i++) { 95 | distributionSummary.record(NORMAL_SIZE); 96 | } 97 | //one outlier 98 | distributionSummary.record(OUTLIER_SIZE); 99 | 100 | 101 | //then 102 | List measurements = new ArrayList<>(); 103 | metricRegistry.findMeter(Meter.Type.DistributionSummary, "request-summary.size") 104 | .get().measure().iterator().forEachRemaining(measurements::add); 105 | 106 | List result = extractPercentilesAsMap(measurements, "request-summary.size_bucket"); 107 | assertThat(result) 108 | .contains("10.0=2.0", "20.0=100.0", "+Inf=1.0"); 109 | 110 | } 111 | 112 | //continue from here https://www.baeldung.com/micrometer 113 | 114 | private List extractPercentilesAsMap(List measurements, String name) { 115 | List result = measurements 116 | .stream() 117 | .filter(m -> m.getName().equals(name)) 118 | .map(m -> m.getTags().first().getValue() + "=" + m.getValue()).collect(Collectors.toList()); 119 | ; 120 | return result; 121 | } 122 | 123 | 124 | } 125 | --------------------------------------------------------------------------------