├── .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 |
10 | - How to avoid common Dependency Injection pitfalls
11 |
- Use scopes of beans to control component lifecycles
12 |
- Leverage Spring profiles to load environment-specific configurations
13 |
- Use programmatic configuration over XML to define beans
14 |
- Use Spring REST constructs to create a robust API
15 |
- Make your tests more maintainable
16 |
- Create fault-tolerant microservices by the proper configuration of REST templates
17 |
- Make production applications more maintainable with robust monitoring
18 |
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