├── .coveralls.yml
├── .gitignore
├── .java-version
├── .travis.yml
├── LICENSE
├── README.md
├── build.gradle
├── codequality
└── HEADER
├── gradle.properties
├── gradle
├── license.gradle
├── release.gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── libraries.gradle
└── src
├── main
└── java
│ └── io
│ └── jmnarloch
│ └── spring
│ └── request
│ └── correlation
│ ├── api
│ ├── CorrelationIdGenerator.java
│ ├── EnableRequestCorrelation.java
│ ├── RequestCorrelation.java
│ └── RequestCorrelationInterceptor.java
│ ├── feign
│ ├── FeignCorrelationConfiguration.java
│ └── FeignCorrelationInterceptor.java
│ ├── filter
│ ├── DefaultRequestCorrelation.java
│ └── RequestCorrelationFilter.java
│ ├── generator
│ └── UuidGenerator.java
│ ├── http
│ ├── ClientHttpCorrelationConfiguration.java
│ └── ClientHttpRequestCorrelationInterceptor.java
│ └── support
│ ├── RequestCorrelationConfiguration.java
│ ├── RequestCorrelationConsts.java
│ ├── RequestCorrelationProperties.java
│ └── RequestCorrelationUtils.java
└── test
├── java
└── io
│ └── jmnarloch
│ └── spring
│ └── request
│ └── correlation
│ ├── CorrelationTestUtils.java
│ ├── Demo.java
│ ├── feign
│ └── FeignCorrelationInterceptorTest.java
│ ├── filter
│ └── RequestCorrelationFilterTest.java
│ ├── generator
│ └── UuidGeneratorTest.java
│ ├── http
│ └── ClientHttpRequestCorrelationInterceptorTest.java
│ └── support
│ └── RequestCorrelationUtilsTest.java
└── resources
└── application.yml
/.coveralls.yml:
--------------------------------------------------------------------------------
1 | repo_token: GePGL0UeMhfAkKaGHuXqYCipRrslPcj6T
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Gradle template
3 | .gradle
4 | build/
5 |
6 | # Ignore Gradle GUI config
7 | gradle-app.setting
8 |
9 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
10 | !gradle-wrapper.jar
11 |
12 |
13 | ### NetBeans template
14 | nbproject/private/
15 | build/
16 | nbbuild/
17 | dist/
18 | nbdist/
19 | nbactions.xml
20 | nb-configuration.xml
21 | .nb-gradle/
22 |
23 |
24 | ### JetBrains template
25 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
26 |
27 | *.iml
28 |
29 | ## Directory-based project format:
30 | .idea/
31 | # if you remove the above rule, at least ignore the following:
32 |
33 | # User-specific stuff:
34 | # .idea/workspace.xml
35 | # .idea/tasks.xml
36 | # .idea/dictionaries
37 |
38 | # Sensitive or high-churn files:
39 | # .idea/dataSources.ids
40 | # .idea/dataSources.xml
41 | # .idea/sqlDataSources.xml
42 | # .idea/dynamic.xml
43 | # .idea/uiDesigner.xml
44 |
45 | # Gradle:
46 | # .idea/gradle.xml
47 | # .idea/libraries
48 |
49 | # Mongo Explorer plugin:
50 | # .idea/mongoSettings.xml
51 |
52 | ## File-based project format:
53 | *.ipr
54 | *.iws
55 |
56 | ## Plugin-specific files:
57 |
58 | # IntelliJ
59 | /out/
60 |
61 | # mpeltonen/sbt-idea plugin
62 | .idea_modules/
63 |
64 | # JIRA plugin
65 | atlassian-ide-plugin.xml
66 |
67 | # Crashlytics plugin (for Android Studio and IntelliJ)
68 | com_crashlytics_export_strings.xml
69 | crashlytics.properties
70 | crashlytics-build.properties
71 |
72 |
73 | ### Eclipse template
74 | *.pydevproject
75 | .metadata
76 | .gradle
77 | bin/
78 | tmp/
79 | *.tmp
80 | *.bak
81 | *.swp
82 | *~.nib
83 | local.properties
84 | .settings/
85 | .loadpath
86 |
87 | # Eclipse Core
88 | .project
89 |
90 | # External tool builders
91 | .externalToolBuilders/
92 |
93 | # Locally stored "Eclipse launch configurations"
94 | *.launch
95 |
96 | # CDT-specific
97 | .cproject
98 |
99 | # JDT-specific (Eclipse Java Development Tools)
100 | .classpath
101 |
102 | # PDT-specific
103 | .buildpath
104 |
105 | # sbteclipse plugin
106 | .target
107 |
108 | # TeXlipse plugin
109 | .texlipse
110 |
111 |
112 |
--------------------------------------------------------------------------------
/.java-version:
--------------------------------------------------------------------------------
1 | 1.8
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - oraclejdk7
4 | install:
5 | - ./gradlew assemble -PossrhUsername="${ossrhUsername}" -PossrhPassword="${ossrhPassword}"
6 | script:
7 | - ./gradlew check -PossrhUsername="${ossrhUsername}" -PossrhPassword="${ossrhPassword}"
8 | after_success:
9 | - ./gradlew jacocoTestReport coveralls -PossrhUsername="${ossrhUsername}" -PossrhPassword="${ossrhPassword}"
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Cloud Request Correlation
2 |
3 | > A Spring Cloud starter for easy setup request correlation
4 |
5 | [](https://travis-ci.org/jmnarloch/request-correlation-spring-cloud-starter)
6 | [](https://coveralls.io/github/jmnarloch/request-correlation-spring-cloud-starter?branch=master)
7 |
8 | ## Features
9 |
10 | Allows to uniquely identify and track your request by passing `X-Request-Id` header across remote calls.
11 |
12 | ## Setup
13 |
14 | Add the Spring Cloud starter to your project:
15 |
16 | ```xml
17 |
18 | io.jmnarloch
19 | request-correlation-spring-cloud-starter
20 | 1.2.0
21 |
22 | ```
23 |
24 | ## Usage
25 |
26 | Annotate every Spring Boot / Cloud Application with `@EnableRequestCorrelation` annotation. That's it.
27 |
28 | ```java
29 | @EnableRequestCorrelation
30 | @SpringBootApplication
31 | public class Application {
32 |
33 | }
34 | ```
35 |
36 | ## Properties
37 |
38 | You can configure following options:
39 |
40 | ```
41 | request.correlation.header-name=X-Request-Id # sets the header name to be used for request identification (X-Request-Id by default)
42 | request.correlation.client.http.enabled=true # enables the RestTemplate header propagation (true by default)
43 | request.correlation.client.feign.enabled=true # enables the Fegin header propagation (true by default)
44 | ```
45 |
46 | ## How it works?
47 |
48 | The annotation will auto register servlet filter that will process any inbound request and correlate it with
49 | unique identifier.
50 |
51 | ## Retrieving the request identifier
52 |
53 | You can retrieve the current request id within any request bound thread through
54 | `RequestCorrelationUtils.getCurrentCorrelationId`.
55 |
56 | ## Propagation
57 |
58 | Besides that you will also have transparent integration with fallowing:
59 |
60 | * RestTemplate - any Spring configured `RestTemplate` will be automatically populated with the request id.
61 | * Feign clients - similarly a request interceptor is being registered for Feign clients
62 | * Zuul proxy - any configured route will be also 'enriched' with the identifier
63 |
64 | ## Applications
65 |
66 | The extension itself simply gives you means to propagate the information. How you going to use it is up to you.
67 |
68 | For instance you can apply this information to your logging MDC map. You can achieve that by registering
69 | `RequestCorrelationInterceptor` bean. The `RequestCorrelationInterceptor` gives you only an entry point so that
70 | any fallowing operation would be able to access the correlation identifier. You may also use Spring's
71 | [HandlerInterceptor](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html)
72 | and set the value there.
73 |
74 | ```java
75 | @Bean
76 | public RequestCorrelationInterceptor correlationLoggingInterceptor() {
77 | return new RequestCorrelationInterceptor() {
78 | @Override
79 | public void afterCorrelationIdSet(String correlationId) {
80 | MDC.put("correlationId", correlationId);
81 | }
82 | };
83 | }
84 | ```
85 |
86 | If your are using Vnd.errors you can use that as your logref value
87 |
88 | ```java
89 | @ExceptionHandler
90 | public ResponseEntity error(Exception ex) {
91 |
92 | final VndError vndError = new VndError(RequestCorrelationUtils.getCurrentCorrelationId(), ex.getMessage());
93 |
94 | return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
95 | .header(HttpHeaders.CONTENT_TYPE, "application/vnd.error+json")
96 | .body(vndError);
97 | }
98 | ```
99 |
100 | Another use case is to save that with your Spring Boot Actuator's audits when you implement custom `AuditEventRepository`.
101 |
102 | ## Migrating to 1.1
103 |
104 | The properties enable has been renamed to enabled to match the Spring convention, besides that there are active by default
105 |
106 | ## License
107 |
108 | Apache 2.0
109 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | jcenter()
4 | }
5 | }
6 |
7 | plugins {
8 | id "com.github.hierynomus.license" version "0.11.0"
9 | id 'net.researchgate.release' version '2.1.2'
10 | id 'com.github.kt3k.coveralls' version '2.4.0'
11 | }
12 |
13 | apply plugin: 'java'
14 | apply plugin: "jacoco"
15 | apply plugin: 'idea'
16 |
17 | apply from: 'libraries.gradle'
18 | apply from: 'gradle/license.gradle'
19 | apply from: 'gradle/release.gradle'
20 |
21 | apply plugin: 'findbugs'
22 | apply plugin: 'pmd'
23 |
24 | apply plugin: 'com.github.kt3k.coveralls'
25 |
26 | sourceCompatibility = 1.7
27 |
28 | group = "io.jmnarloch"
29 | archivesBaseName="request-correlation-spring-cloud-starter"
30 |
31 | ext {
32 | isReleaseVersion = !version.endsWith("SNAPSHOT")
33 | }
34 |
35 | task wrapper(type: Wrapper) {
36 | gradleVersion = '2.9'
37 | }
38 |
39 | jar {
40 | manifest {
41 | attributes 'Implementation-Title': 'request-correlation-spring-cloud-starter',
42 | 'Implementation-Version': version
43 | }
44 | }
45 |
46 | repositories {
47 | jcenter()
48 | }
49 |
50 | compileJava {
51 | options.fork = true
52 | }
53 |
54 | dependencies {
55 |
56 | compile (libraries.springBootWeb)
57 | compile (libraries.springCloudFeign)
58 | compile (libraries.commonsLang)
59 |
60 | testCompile (libraries.springBootTest)
61 | testCompile (libraries.junit)
62 | testCompile (libraries.mockito)
63 | }
64 |
65 | findbugs {
66 | ignoreFailures = true
67 | }
68 |
69 | jacocoTestReport {
70 | reports {
71 | xml.enabled = true
72 | html.enabled = true
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/codequality/HEADER:
--------------------------------------------------------------------------------
1 | Copyright (c) ${year} the original author or authors
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #Fri, 02 Oct 2015 22:11:47 +0200
2 | version=1.2.1-SNAPSHOT
3 |
--------------------------------------------------------------------------------
/gradle/license.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'license'
2 |
3 | license {
4 |
5 | header rootProject.file('codequality/HEADER')
6 | strictCheck true
7 | skipExistingHeaders true
8 | include "**/*.java"
9 |
10 | ext.year = Calendar.getInstance().get(Calendar.YEAR)
11 | }
--------------------------------------------------------------------------------
/gradle/release.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven'
2 | apply plugin: 'signing'
3 | apply plugin: 'net.researchgate.release'
4 |
5 | task javadocJar(type: Jar) {
6 | classifier = 'javadoc'
7 | from javadoc
8 | }
9 |
10 | task sourcesJar(type: Jar) {
11 | classifier = 'sources'
12 | from sourceSets.main.allSource
13 | }
14 |
15 | artifacts {
16 | archives javadocJar, sourcesJar
17 | }
18 |
19 | signing {
20 | required { isReleaseVersion && gradle.taskGraph.hasTask("uploadArchives") }
21 | sign configurations.archives
22 | }
23 |
24 | uploadArchives {
25 | repositories {
26 | mavenDeployer {
27 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
28 |
29 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
30 | authentication(userName: rootProject.hasProperty('ossrhUsername') ? rootProject.ossrhUsername : '', password: rootProject.hasProperty('ossrhPassword') ? rootProject.ossrhPassword : '')
31 | }
32 |
33 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
34 | authentication(userName: rootProject.hasProperty('ossrhUsername') ? rootProject.ossrhUsername : '', password: rootProject.hasProperty('ossrhPassword') ? rootProject.ossrhPassword : '')
35 | }
36 |
37 | pom.project {
38 | name 'request-correlation-spring-cloud-starter'
39 | packaging 'jar'
40 | description 'Spring Cloud Request Correlation'
41 | url 'https://github.com/jmnarloch/request-correlation-spring-cloud-starter'
42 |
43 | scm {
44 | connection 'scm:git:https://github.com/jmnarloch/request-correlation-spring-cloud-starter.git'
45 | developerConnection 'scm:git:https://github.com/jmnarloch/request-correlation-spring-cloud-starter.git'
46 | url 'https://github.com/jmnarloch/request-correlation-spring-cloud-starter.git'
47 | }
48 |
49 | licenses {
50 | license {
51 | name 'The Apache License, Version 2.0'
52 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
53 | }
54 | }
55 |
56 | developers {
57 | developer {
58 | id 'jmnarloch'
59 | name 'Jakub Narloch'
60 | email 'jmnarloch@gmail.com'
61 | }
62 | }
63 | }
64 | }
65 | }
66 | }
67 |
68 | release {
69 | tagTemplate = '${version}'
70 |
71 | git {
72 | requireBranch = 'master'
73 | pushToRemote = 'origin'
74 | pushToCurrentBranch = false
75 | }
76 | }
77 | afterReleaseBuild.dependsOn uploadArchives
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jmnarloch/request-correlation-spring-cloud-starter/0a528eda87d4088519cca3b252b9d9dfcfe76426/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Dec 25 15:01:25 CET 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.9-bin.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/libraries.gradle:
--------------------------------------------------------------------------------
1 | ext {
2 |
3 | libraries = [
4 |
5 | springBootWeb: 'org.springframework.boot:spring-boot-starter-web:1.2.5.RELEASE',
6 | springCloudFeign: 'org.springframework.cloud:spring-cloud-starter-feign:1.0.3.RELEASE',
7 | commonsLang: 'org.apache.commons:commons-lang3:3.4',
8 |
9 | springBootTest: 'org.springframework.boot:spring-boot-starter-test:1.2.5.RELEASE',
10 |
11 | junit : 'junit:junit:4.12',
12 | mockito : 'org.mockito:mockito-all:1.10.19'
13 | ]
14 | }
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/api/CorrelationIdGenerator.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.api;
17 |
18 | /**
19 | * Request id generation abstraction, allows to implement different strategies for request id generation.
20 | *
21 | * @author Jakub Narloch
22 | */
23 | public interface CorrelationIdGenerator {
24 |
25 | /**
26 | * Generates the request id.
27 | *
28 | * @return generated the request id
29 | */
30 | String generate();
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/api/EnableRequestCorrelation.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.api;
17 |
18 | import io.jmnarloch.spring.request.correlation.http.ClientHttpCorrelationConfiguration;
19 | import io.jmnarloch.spring.request.correlation.feign.FeignCorrelationConfiguration;
20 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConfiguration;
21 | import org.springframework.context.annotation.Import;
22 | import org.springframework.web.client.RestTemplate;
23 |
24 | import java.lang.annotation.*;
25 |
26 | /**
27 | * Enables automatic request correlation by assigning per each request unique identifier that afterwards is being
28 | * propagated through 'X-Request-Id' header.
29 | *
30 | * By default the identifier will be generated using random {@code UUID}.
31 | *
32 | * The header will be automatically propagated through any Spring configured {@link RestTemplate} bean or Feign client.
33 | *
34 | * @author Jakub Narloch
35 | * @see RequestCorrelation
36 | * @see RequestCorrelationConfiguration
37 | * @see CorrelationIdGenerator
38 | */
39 | @Documented
40 | @Inherited
41 | @Retention(RetentionPolicy.RUNTIME)
42 | @Target(ElementType.TYPE)
43 | @Import({
44 | RequestCorrelationConfiguration.class,
45 | ClientHttpCorrelationConfiguration.class,
46 | FeignCorrelationConfiguration.class
47 | })
48 | public @interface EnableRequestCorrelation {
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/api/RequestCorrelation.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.api;
17 |
18 | /**
19 | * Holder for the request correlation id.
20 | *
21 | * @author Jakub Narloch
22 | */
23 | public interface RequestCorrelation {
24 |
25 | /**
26 | * Returns the request correlation id.
27 | *
28 | * @return the request correlation id
29 | */
30 | String getRequestId();
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/api/RequestCorrelationInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.api;
17 |
18 | /**
19 | * An interceptor that can be used for
20 | *
21 | * @author Jakub Narloch
22 | */
23 | public interface RequestCorrelationInterceptor {
24 |
25 | /**
26 | * Callback method called whenever the correlation id has been assigned for the current request. No matter whether
27 | * it has set from the request header or a new id has been generated for incoming request.
28 | *
29 | * @param correlationId the correlation id
30 | */
31 | void afterCorrelationIdSet(String correlationId);
32 |
33 | /**
34 | * Callback method called after filter chain has completed.
35 | *
36 | * @param correlationId the correlation id
37 | */
38 | void cleanUp(String correlationId);
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/feign/FeignCorrelationConfiguration.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.feign;
17 |
18 | import feign.Feign;
19 | import feign.RequestInterceptor;
20 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
21 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
22 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
23 | import org.springframework.context.annotation.Bean;
24 | import org.springframework.context.annotation.Configuration;
25 |
26 | /**
27 | * Adds Feign's {@link RequestInterceptor} for propagating the correlation id.
28 | *
29 | * @author Jakub Narloch
30 | */
31 | @Configuration
32 | @ConditionalOnClass(Feign.class)
33 | @ConditionalOnProperty(value = "request.correlation.client.feign.enabled", matchIfMissing = true)
34 | public class FeignCorrelationConfiguration {
35 |
36 | @Bean
37 | public RequestInterceptor feignCorrelationInterceptor(RequestCorrelationProperties properties) {
38 | return new FeignCorrelationInterceptor(properties);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/feign/FeignCorrelationInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.feign;
17 |
18 | import feign.RequestInterceptor;
19 | import feign.RequestTemplate;
20 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConsts;
21 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
22 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationUtils;
23 | import org.springframework.util.Assert;
24 |
25 | /**
26 | * Feign request correlation interceptor.
27 | *
28 | * @author Jakub Narloch
29 | */
30 | public class FeignCorrelationInterceptor implements RequestInterceptor {
31 |
32 | /**
33 | * The correlation properties.
34 | */
35 | private final RequestCorrelationProperties properties;
36 |
37 | /**
38 | * Creates new instance of {@link FeignCorrelationInterceptor}.
39 | *
40 | * @param properties the correlation properties
41 | *
42 | * @throws IllegalArgumentException if {@code properties} is {@code null}
43 | */
44 | public FeignCorrelationInterceptor(RequestCorrelationProperties properties) {
45 | Assert.notNull(properties, "Parameter 'properties' can not be null");
46 |
47 | this.properties = properties;
48 | }
49 |
50 | /**
51 | * {@inheritDoc}
52 | */
53 | @Override
54 | public void apply(RequestTemplate template) {
55 |
56 | final String correlationId = RequestCorrelationUtils.getCurrentCorrelationId();
57 | if(correlationId != null) {
58 | template.header(RequestCorrelationConsts.HEADER_NAME, correlationId);
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/filter/DefaultRequestCorrelation.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.filter;
17 |
18 | import io.jmnarloch.spring.request.correlation.api.RequestCorrelation;
19 |
20 | /**
21 | * Base implementation of {@link RequestCorrelation}.
22 | *
23 | * @author Jakub Narloch
24 | */
25 | public final class DefaultRequestCorrelation implements RequestCorrelation {
26 |
27 | /**
28 | * The actual request correlation id.
29 | */
30 | private final String id;
31 |
32 | /**
33 | * Creates new instance of {@link DefaultRequestCorrelation} class.
34 | *
35 | * @param id the request id
36 | */
37 | public DefaultRequestCorrelation(String id) {
38 | this.id = id;
39 | }
40 |
41 | /**
42 | * Retrieves the request identifier.
43 | *
44 | * @return the request identifier
45 | */
46 | @Override
47 | public String getRequestId() {
48 | return id;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/filter/RequestCorrelationFilter.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.filter;
17 |
18 | import io.jmnarloch.spring.request.correlation.api.CorrelationIdGenerator;
19 | import io.jmnarloch.spring.request.correlation.api.RequestCorrelation;
20 | import io.jmnarloch.spring.request.correlation.api.RequestCorrelationInterceptor;
21 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConsts;
22 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
23 | import org.apache.commons.lang3.StringUtils;
24 | import org.slf4j.Logger;
25 | import org.slf4j.LoggerFactory;
26 | import org.springframework.util.Assert;
27 |
28 | import javax.servlet.*;
29 | import javax.servlet.http.HttpServletRequest;
30 | import javax.servlet.http.HttpServletRequestWrapper;
31 | import javax.servlet.http.HttpServletResponse;
32 | import java.io.IOException;
33 | import java.util.*;
34 | import java.util.concurrent.ConcurrentHashMap;
35 |
36 | /**
37 | * The entry point for the request correlation. This filter intercepts any incoming request and in case that it
38 | * does not contain the correlation header creates new identifier and stores it both as the request header
39 | * and also as a attribute.
40 | *
41 | * @author Jakub Narloch
42 | * @author Souris Stathis
43 | */
44 | public class RequestCorrelationFilter implements Filter {
45 |
46 | /**
47 | * Logger instance used by this class.
48 | */
49 | private final Logger logger = LoggerFactory.getLogger(RequestCorrelationFilter.class);
50 |
51 | /**
52 | * The request generator used for generating new identifiers.
53 | */
54 | private final CorrelationIdGenerator correlationIdGenerator;
55 |
56 | /**
57 | * List of optional interceptors.
58 | */
59 | private final List interceptors;
60 |
61 | /**
62 | * The request correlation properties.
63 | */
64 | private final RequestCorrelationProperties properties;
65 |
66 | /**
67 | * Creates new instance of {@link CorrelationIdGenerator} class.
68 | *
69 | * @param correlationIdGenerator the request id generator
70 | * @param interceptors the correlation interceptors
71 | * @param properties the request properties
72 | * @throws IllegalArgumentException if {@code requestIdGenerator} is {@code null}
73 | * or {@code interceptors} is {@code null}
74 | * or {@code properties} is {@code null}
75 | */
76 | public RequestCorrelationFilter(CorrelationIdGenerator correlationIdGenerator,
77 | List interceptors, RequestCorrelationProperties properties) {
78 | Assert.notNull(correlationIdGenerator, "Parameter 'correlationIdGenerator' can not be null.");
79 | Assert.notNull(interceptors, "Parameter 'interceptors' can not be null.");
80 | Assert.notNull(properties, "Parameter 'properties' can not be null.");
81 |
82 | this.correlationIdGenerator = correlationIdGenerator;
83 | this.interceptors = interceptors;
84 | this.properties = properties;
85 | }
86 |
87 | /**
88 | * {@inheritDoc}
89 | */
90 | @Override
91 | public void init(FilterConfig filterConfig) throws ServletException {
92 | // empty method
93 | }
94 |
95 | /**
96 | * {@inheritDoc}
97 | */
98 | @Override
99 | public void destroy() {
100 | // empty method
101 | }
102 |
103 | /**
104 | * {@inheritDoc}
105 | */
106 | @Override
107 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
108 |
109 | if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
110 | doHttpFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
111 | } else {
112 | // otherwise just pass through
113 | chain.doFilter(request, response);
114 | }
115 | }
116 |
117 | /**
118 | * Performs 'enrichment' of incoming HTTP request.
119 | *
120 | * @param request the http servlet request
121 | * @param response the http servlet response
122 | * @param chain the filter processing chain
123 | * @throws IOException if any error occurs
124 | * @throws ServletException if any error occurs
125 | */
126 | private void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
127 |
128 | // retrieves the correlationId
129 | String correlationId = getCorrelationId(request);
130 |
131 | // verifies the correlation id was set
132 | if (StringUtils.isBlank(correlationId)) {
133 | correlationId = generateCorrelationId();
134 | logger.debug("Request correlation id was not present, generating new one: {}", correlationId);
135 | }
136 |
137 | // triggers interceptors
138 | triggerInterceptors(correlationId);
139 |
140 | // instantiates new request correlation
141 | final RequestCorrelation requestCorrelation = new DefaultRequestCorrelation(correlationId);
142 |
143 | // populates the attribute
144 | final ServletRequest req = enrichRequest(request, requestCorrelation);
145 |
146 | try {
147 | // proceeds with execution
148 | chain.doFilter(req, response);
149 | } finally {
150 | triggerInterceptorsCleanup(correlationId);
151 | }
152 | }
153 |
154 | /**
155 | * Retrieves the correlation id from the request, if present.
156 | *
157 | * @param request the http servlet request
158 | * @return the correlation id
159 | */
160 | private String getCorrelationId(HttpServletRequest request) {
161 |
162 | return request.getHeader(properties.getHeaderName());
163 | }
164 |
165 | /**
166 | * Generates new correlation id.
167 | *
168 | * @return the correlation id
169 | */
170 | private String generateCorrelationId() {
171 |
172 | return correlationIdGenerator.generate();
173 | }
174 |
175 | /**
176 | * Triggers the configured interceptors.
177 | *
178 | * @param correlationId the correlation id
179 | */
180 | private void triggerInterceptors(String correlationId) {
181 |
182 | for (RequestCorrelationInterceptor interceptor : interceptors) {
183 | interceptor.afterCorrelationIdSet(correlationId);
184 | }
185 | }
186 |
187 | /**
188 | * Triggers the configured interceptors cleanUp methods.
189 | *
190 | * @param correlationId the correlation id
191 | */
192 | private void triggerInterceptorsCleanup(String correlationId) {
193 |
194 | for (RequestCorrelationInterceptor interceptor : interceptors) {
195 | interceptor.cleanUp(correlationId);
196 | }
197 | }
198 |
199 | /**
200 | * "Enriches" the request.
201 | *
202 | * @param request the http servlet request
203 | * @param correlationId the correlation id
204 | * @return the servlet request
205 | */
206 | private ServletRequest enrichRequest(HttpServletRequest request, RequestCorrelation correlationId) {
207 |
208 | final CorrelatedServletRequest req = new CorrelatedServletRequest(request);
209 | req.setAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME, correlationId);
210 | req.setHeader(properties.getHeaderName(), correlationId.getRequestId());
211 | return req;
212 | }
213 |
214 | /**
215 | * An http servlet wrapper that allows to register additional HTTP headers.
216 | *
217 | * @author Jakub Narloch
218 | */
219 | private static class CorrelatedServletRequest extends HttpServletRequestWrapper {
220 |
221 | /**
222 | * Map with additional customizable headers.
223 | */
224 | private final Map additionalHeaders = new ConcurrentHashMap<>();
225 |
226 | /**
227 | * Creates a ServletRequest adaptor wrapping the given request object.
228 | *
229 | * @param request The request to wrap
230 | * @throws IllegalArgumentException if the request is null
231 | */
232 | public CorrelatedServletRequest(HttpServletRequest request) {
233 | super(request);
234 | }
235 |
236 | /**
237 | * Sets the header value.
238 | *
239 | * @param key the header name
240 | * @param value the header value
241 | */
242 | public void setHeader(String key, String value) {
243 |
244 | this.additionalHeaders.put(key, value);
245 | }
246 |
247 | @Override
248 | public String getHeader(String name) {
249 | if (additionalHeaders.containsKey(name)) {
250 | return additionalHeaders.get(name);
251 | }
252 | return super.getHeader(name);
253 | }
254 |
255 | @Override
256 | public Enumeration getHeaders(String name) {
257 |
258 | final List values = new ArrayList<>();
259 | if (additionalHeaders.containsKey(name)) {
260 | values.add(additionalHeaders.get(name));
261 | } else {
262 | values.addAll(Collections.list(super.getHeaders(name)));
263 | }
264 | return Collections.enumeration(values);
265 | }
266 |
267 | @Override
268 | public Enumeration getHeaderNames() {
269 |
270 | final Set names = new HashSet<>();
271 | names.addAll(additionalHeaders.keySet());
272 | names.addAll(Collections.list(super.getHeaderNames()));
273 | return Collections.enumeration(names);
274 | }
275 | }
276 | }
277 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/generator/UuidGenerator.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.generator;
17 |
18 | import io.jmnarloch.spring.request.correlation.api.CorrelationIdGenerator;
19 |
20 | import java.util.UUID;
21 |
22 | /**
23 | * Uses {@link UUID#randomUUID()} for generating new requests ids.
24 | *
25 | * @author Jakub Narloch
26 | */
27 | public class UuidGenerator implements CorrelationIdGenerator {
28 |
29 | /**
30 | * Generates new request id as random UUID.
31 | *
32 | * @return random uuid
33 | */
34 | @Override
35 | public String generate() {
36 |
37 | return UUID.randomUUID().toString();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/http/ClientHttpCorrelationConfiguration.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.http;
17 |
18 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
19 | import org.springframework.beans.factory.InitializingBean;
20 | import org.springframework.beans.factory.annotation.Autowired;
21 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
22 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
23 | import org.springframework.context.annotation.Bean;
24 | import org.springframework.context.annotation.Configuration;
25 | import org.springframework.http.client.ClientHttpRequestInterceptor;
26 | import org.springframework.http.client.support.InterceptingHttpAccessor;
27 |
28 | import java.util.ArrayList;
29 | import java.util.List;
30 |
31 | /**
32 | * Configures any {@link org.springframework.web.client.RestTemplate} bean by adding additional request interceptor.
33 | *
34 | * @author Jakub Narloch
35 | */
36 | @Configuration
37 | @ConditionalOnClass(InterceptingHttpAccessor.class)
38 | @ConditionalOnProperty(value = "request.correlation.client.http.enabled", matchIfMissing = true)
39 | public class ClientHttpCorrelationConfiguration {
40 |
41 | @Autowired(required = false)
42 | private List clients = new ArrayList<>();
43 |
44 | @Bean
45 | public InitializingBean clientsCorrelationInitializer(final RequestCorrelationProperties properties) {
46 |
47 | return new InitializingBean() {
48 | @Override
49 | public void afterPropertiesSet() throws Exception {
50 |
51 | if(clients != null) {
52 | for(InterceptingHttpAccessor client : clients) {
53 | final List interceptors = new ArrayList<>(client.getInterceptors());
54 | interceptors.add(new ClientHttpRequestCorrelationInterceptor(properties));
55 | client.setInterceptors(interceptors);
56 | }
57 | }
58 | }
59 | };
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/http/ClientHttpRequestCorrelationInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.http;
17 |
18 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConsts;
19 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
20 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationUtils;
21 | import org.springframework.http.HttpRequest;
22 | import org.springframework.http.client.ClientHttpRequestExecution;
23 | import org.springframework.http.client.ClientHttpRequestInterceptor;
24 | import org.springframework.http.client.ClientHttpResponse;
25 | import org.springframework.util.Assert;
26 |
27 | import java.io.IOException;
28 |
29 | /**
30 | * Rest template http interceptor, that propagates the currents thread bound request identifier to the outgoing request,
31 | * through 'X-Request-Id' header.
32 | *
33 | * @author Jakub Narloch
34 | */
35 | public class ClientHttpRequestCorrelationInterceptor implements ClientHttpRequestInterceptor {
36 |
37 | /**
38 | * The correlation properties.
39 | */
40 | private final RequestCorrelationProperties properties;
41 |
42 | /**
43 | * Creates new instance of {@link ClientHttpRequestCorrelationInterceptor}.
44 | *
45 | * @param properties the properties
46 | * @throws IllegalArgumentException if {@code properties} is {@code null}
47 | */
48 | public ClientHttpRequestCorrelationInterceptor(RequestCorrelationProperties properties) {
49 | Assert.notNull(properties, "Parameter 'properties' can not be null");
50 |
51 | this.properties = properties;
52 | }
53 |
54 | /**
55 | * {@inheritDoc}
56 | */
57 | @Override
58 | public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
59 |
60 | // sets the correlation id
61 | final String correlationId = RequestCorrelationUtils.getCurrentCorrelationId();
62 | if(correlationId != null) {
63 | request.getHeaders().add(RequestCorrelationConsts.HEADER_NAME, correlationId);
64 | }
65 |
66 | // proceeds with execution
67 | return execution.execute(request, body);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/support/RequestCorrelationConfiguration.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.support;
17 |
18 | import io.jmnarloch.spring.request.correlation.api.CorrelationIdGenerator;
19 | import io.jmnarloch.spring.request.correlation.api.RequestCorrelationInterceptor;
20 | import io.jmnarloch.spring.request.correlation.filter.RequestCorrelationFilter;
21 | import io.jmnarloch.spring.request.correlation.generator.UuidGenerator;
22 | import org.springframework.beans.factory.annotation.Autowired;
23 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
24 | import org.springframework.boot.context.embedded.FilterRegistrationBean;
25 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
26 | import org.springframework.context.annotation.Bean;
27 | import org.springframework.context.annotation.Configuration;
28 | import org.springframework.core.Ordered;
29 |
30 | import javax.servlet.DispatcherType;
31 | import java.util.ArrayList;
32 | import java.util.EnumSet;
33 | import java.util.List;
34 |
35 | /**
36 | * Configures the request correlation filter.
37 | *
38 | * @author Jakub Narloch
39 | * @see io.jmnarloch.spring.request.correlation.api.EnableRequestCorrelation
40 | */
41 | @Configuration
42 | @EnableConfigurationProperties
43 | public class RequestCorrelationConfiguration {
44 |
45 | @Autowired(required = false)
46 | private List interceptors = new ArrayList<>();
47 |
48 | @Bean
49 | public RequestCorrelationProperties requestCorrelationProperties() {
50 | return new RequestCorrelationProperties();
51 | }
52 |
53 | @Bean
54 | @ConditionalOnMissingBean(CorrelationIdGenerator.class)
55 | public CorrelationIdGenerator requestIdGenerator() {
56 | return new UuidGenerator();
57 | }
58 |
59 | @Bean
60 | public RequestCorrelationFilter requestCorrelationFilter(CorrelationIdGenerator generator, RequestCorrelationProperties properties) {
61 |
62 | return new RequestCorrelationFilter(generator, interceptors, properties);
63 | }
64 |
65 | @Bean
66 | public FilterRegistrationBean requestCorrelationFilterBean(RequestCorrelationFilter correlationFilter) {
67 |
68 | final FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
69 | filterRegistration.setFilter(correlationFilter);
70 | filterRegistration.setMatchAfter(false);
71 | filterRegistration.setDispatcherTypes(
72 | EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
73 | filterRegistration.setAsyncSupported(true);
74 | filterRegistration.setOrder(Ordered.HIGHEST_PRECEDENCE);
75 | return filterRegistration;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/support/RequestCorrelationConsts.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.support;
17 |
18 | /**
19 | * Lists the constants used by this component.
20 | *
21 | * @author Jakub Narloch
22 | */
23 | public interface RequestCorrelationConsts {
24 |
25 | /**
26 | * The request correlation header name.
27 | */
28 | String HEADER_NAME = "X-Request-Id";
29 |
30 | /**
31 | * The request attribute name.
32 | */
33 | String ATTRIBUTE_NAME = "io.jmnarloch.spring.request.correlation.api.RequestCorrelation.ATTRIBUTE";
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/support/RequestCorrelationProperties.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.support;
17 |
18 | /**
19 | * The request correlation properties.
20 | *
21 | * @author Jakub Narloch
22 | */
23 | public class RequestCorrelationProperties {
24 |
25 | /**
26 | * Header name.
27 | */
28 | private String headerName = RequestCorrelationConsts.HEADER_NAME;
29 |
30 | /**
31 | * Creates new instance of {@link RequestCorrelationProperties} class.
32 | */
33 | public RequestCorrelationProperties() {
34 | }
35 |
36 | /**
37 | * Retrieves the header names.
38 | *
39 | * @return the header names
40 | */
41 | public String getHeaderName() {
42 | return headerName;
43 | }
44 |
45 | /**
46 | * Sets the header names.
47 | *
48 | * @param headerName the header names
49 | */
50 | public void setHeaderName(String headerName) {
51 | this.headerName = headerName;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/io/jmnarloch/spring/request/correlation/support/RequestCorrelationUtils.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.support;
17 |
18 | import io.jmnarloch.spring.request.correlation.api.RequestCorrelation;
19 | import org.springframework.web.context.request.RequestAttributes;
20 | import org.springframework.web.context.request.RequestContextHolder;
21 |
22 | /**
23 | * A utility class for retrieving the currently bound request correlation id.
24 | *
25 | * @author Jakub Narloch
26 | */
27 | public class RequestCorrelationUtils {
28 |
29 | /**
30 | * Retrieves the current request correlation id if present.
31 | *
32 | * @return the correlation id or {@code null}
33 | */
34 | @SuppressWarnings("unchecked")
35 | public static String getCurrentCorrelationId() {
36 |
37 | final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
38 | if (requestAttributes != null) {
39 | Object correlationId = requestAttributes
40 | .getAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME, RequestAttributes.SCOPE_REQUEST);
41 |
42 | if (correlationId instanceof RequestCorrelation) {
43 | return ((RequestCorrelation) correlationId).getRequestId();
44 | }
45 | }
46 | return null;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/test/java/io/jmnarloch/spring/request/correlation/CorrelationTestUtils.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation;
17 |
18 | import io.jmnarloch.spring.request.correlation.filter.DefaultRequestCorrelation;
19 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConsts;
20 | import org.springframework.web.context.request.RequestAttributes;
21 | import org.springframework.web.context.request.RequestContextHolder;
22 |
23 | /**
24 | * An convinient utility class.
25 | *
26 | * @author Jakub Narloch
27 | */
28 | public class CorrelationTestUtils {
29 |
30 | /**
31 | * Sets the request correlation id.
32 | *
33 | * @param requestId the request id
34 | */
35 | public static void setRequestId(String requestId) {
36 | RequestContextHolder.getRequestAttributes().setAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME,
37 | new DefaultRequestCorrelation(requestId), RequestAttributes.SCOPE_REQUEST);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/io/jmnarloch/spring/request/correlation/Demo.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation;
17 |
18 | import com.netflix.loadbalancer.BaseLoadBalancer;
19 | import com.netflix.loadbalancer.ILoadBalancer;
20 | import com.netflix.loadbalancer.Server;
21 | import io.jmnarloch.spring.request.correlation.api.EnableRequestCorrelation;
22 | import org.junit.Test;
23 | import org.junit.runner.RunWith;
24 | import org.springframework.beans.factory.annotation.Autowired;
25 | import org.springframework.beans.factory.annotation.Value;
26 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
27 | import org.springframework.boot.test.IntegrationTest;
28 | import org.springframework.boot.test.SpringApplicationConfiguration;
29 | import org.springframework.cloud.netflix.feign.EnableFeignClients;
30 | import org.springframework.cloud.netflix.feign.FeignClient;
31 | import org.springframework.cloud.netflix.ribbon.RibbonClient;
32 | import org.springframework.context.annotation.Bean;
33 | import org.springframework.context.annotation.Configuration;
34 | import org.springframework.http.HttpStatus;
35 | import org.springframework.http.ResponseEntity;
36 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
37 | import org.springframework.test.context.web.WebAppConfiguration;
38 | import org.springframework.web.bind.annotation.RequestHeader;
39 | import org.springframework.web.bind.annotation.RequestMapping;
40 | import org.springframework.web.bind.annotation.RequestMethod;
41 | import org.springframework.web.bind.annotation.RestController;
42 | import org.springframework.web.client.RestTemplate;
43 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
44 |
45 | import java.util.Collections;
46 |
47 | import static org.junit.Assert.assertNotNull;
48 |
49 | /**
50 | * Demonstrates the usage of this component.
51 | *
52 | * @author Jakub Narloch
53 | */
54 | @WebAppConfiguration
55 | @IntegrationTest({"server.port=0"})
56 | @SpringApplicationConfiguration(classes = {Demo.Application.class})
57 | @RunWith(SpringJUnit4ClassRunner.class)
58 | public class Demo {
59 |
60 | @Value("${local.server.port}")
61 | private int port;
62 |
63 | @Autowired
64 | private RestTemplate restTemplate;
65 |
66 | @Test
67 | public void test() {
68 |
69 | // when
70 | final String requestId = restTemplate.getForObject(url("/"), String.class);
71 | assertNotNull(requestId);
72 | }
73 |
74 | @Test
75 | public void testRestTemplate() {
76 |
77 | // when
78 | final String requestId = restTemplate.getForObject(url("/rest"), String.class);
79 | assertNotNull(requestId);
80 | }
81 |
82 | @Test
83 | public void testFeign() {
84 |
85 | // when
86 | final String requestId = restTemplate.getForObject(url("/feign"), String.class);
87 | assertNotNull(requestId);
88 | }
89 |
90 | private String url(String path) {
91 |
92 | return String.format("http://127.0.0.1:%d/%s", port, path);
93 | }
94 |
95 | @FeignClient("local")
96 | interface CorrelatedFeignClient {
97 |
98 | @RequestMapping(value = "/", method = RequestMethod.GET)
99 | String getRequestId();
100 | }
101 |
102 | @RestController
103 | @EnableAutoConfiguration
104 | @EnableRequestCorrelation
105 | @EnableFeignClients
106 | @RibbonClient(name = "local", configuration = LocalRibbonClientConfiguration.class)
107 | public static class Application {
108 |
109 | @Autowired
110 | private RestTemplate template;
111 |
112 | @Autowired
113 | private CorrelatedFeignClient feignClient;
114 |
115 | @Bean
116 | public RestTemplate restTemplate() {
117 | return new RestTemplate();
118 | }
119 |
120 | @RequestMapping(value = "/", method = RequestMethod.GET)
121 | public ResponseEntity headerEcho(@RequestHeader(value = "X-Request-Id") String requestId) {
122 |
123 | return ResponseEntity.ok(requestId);
124 | }
125 |
126 | @RequestMapping(value = "/rest", method = RequestMethod.GET)
127 | public ResponseEntity propagateRestTemplate(@RequestHeader(value = "X-Request-Id") String requestId) {
128 |
129 | final String response = restTemplate().getForObject(url("/"), String.class);
130 | if(!requestId.equals(response)) {
131 | return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
132 | }
133 | return ResponseEntity.ok(response);
134 | }
135 |
136 | @RequestMapping(value = "/feign", method = RequestMethod.GET)
137 | public ResponseEntity propagateFeignClient(@RequestHeader(value = "X-Request-Id") String requestId) {
138 |
139 | final String response = feignClient.getRequestId();
140 | if(!requestId.equals(response)) {
141 | return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
142 | }
143 | return ResponseEntity.ok(response);
144 | }
145 |
146 | private String url(String path) {
147 |
148 | return ServletUriComponentsBuilder.fromCurrentRequest().replacePath(path).toUriString();
149 | }
150 | }
151 |
152 | @Configuration
153 | static class LocalRibbonClientConfiguration {
154 |
155 | @Value("${local.server.port}")
156 | private int port = 0;
157 |
158 | @Bean
159 | public ILoadBalancer ribbonLoadBalancer() {
160 | BaseLoadBalancer balancer = new BaseLoadBalancer();
161 | balancer.setServersList(Collections.singletonList(new Server("localhost", this.port)));
162 | return balancer;
163 | }
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/src/test/java/io/jmnarloch/spring/request/correlation/feign/FeignCorrelationInterceptorTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.feign;
17 |
18 | import feign.RequestTemplate;
19 | import io.jmnarloch.spring.request.correlation.CorrelationTestUtils;
20 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConsts;
21 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
22 | import org.junit.After;
23 | import org.junit.Before;
24 | import org.junit.Test;
25 | import org.springframework.mock.web.MockHttpServletRequest;
26 | import org.springframework.web.context.request.RequestContextHolder;
27 | import org.springframework.web.context.request.ServletRequestAttributes;
28 |
29 | import java.util.UUID;
30 |
31 | import static org.junit.Assert.assertEquals;
32 | import static org.junit.Assert.assertFalse;
33 | import static org.junit.Assert.assertTrue;
34 |
35 | /**
36 | * Tests the {@link FeignCorrelationInterceptor} class.
37 | *
38 | * @author Jakub Narloch
39 | */
40 | public class FeignCorrelationInterceptorTest {
41 |
42 | private FeignCorrelationInterceptor instance;
43 |
44 | @Before
45 | public void setUp() throws Exception {
46 |
47 | instance = new FeignCorrelationInterceptor(new RequestCorrelationProperties());
48 | RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
49 | }
50 |
51 | @After
52 | public void tearDown() throws Exception {
53 |
54 | RequestContextHolder.resetRequestAttributes();
55 | }
56 |
57 | @Test
58 | public void shouldSetHeader() {
59 |
60 | // given
61 | final String requestId = UUID.randomUUID().toString();
62 | CorrelationTestUtils.setRequestId(requestId);
63 | final RequestTemplate request = new RequestTemplate();
64 |
65 | // when
66 | instance.apply(request);
67 |
68 | // then
69 | assertTrue(request.headers().containsKey(RequestCorrelationConsts.HEADER_NAME));
70 | assertEquals(1, request.headers().get(RequestCorrelationConsts.HEADER_NAME).size());
71 | assertEquals(requestId, request.headers().get(RequestCorrelationConsts.HEADER_NAME).iterator().next());
72 | }
73 |
74 | @Test
75 | public void shouldNotSetHeader() {
76 |
77 | // given
78 | final RequestTemplate request = new RequestTemplate();
79 |
80 | // when
81 | instance.apply(request);
82 |
83 | // then
84 | assertFalse(request.headers().containsKey(RequestCorrelationConsts.HEADER_NAME));
85 | }
86 |
87 | }
--------------------------------------------------------------------------------
/src/test/java/io/jmnarloch/spring/request/correlation/filter/RequestCorrelationFilterTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.filter;
17 |
18 | import io.jmnarloch.spring.request.correlation.api.CorrelationIdGenerator;
19 | import io.jmnarloch.spring.request.correlation.api.RequestCorrelation;
20 | import io.jmnarloch.spring.request.correlation.api.RequestCorrelationInterceptor;
21 | import io.jmnarloch.spring.request.correlation.generator.UuidGenerator;
22 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConsts;
23 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
24 | import org.junit.Before;
25 | import org.junit.Test;
26 | import org.springframework.mock.web.MockFilterChain;
27 | import org.springframework.mock.web.MockHttpServletRequest;
28 | import org.springframework.mock.web.MockHttpServletResponse;
29 |
30 | import javax.servlet.ServletException;
31 | import javax.servlet.http.HttpServletRequest;
32 | import java.io.IOException;
33 | import java.util.ArrayList;
34 | import java.util.List;
35 | import java.util.UUID;
36 |
37 | import static org.junit.Assert.assertEquals;
38 | import static org.junit.Assert.assertNotNull;
39 | import static org.mockito.Mockito.mock;
40 | import static org.mockito.Mockito.verify;
41 |
42 | /**
43 | * Tests the {@link RequestCorrelationFilter} class.
44 | *
45 | * @author Jakub Narloch
46 | */
47 | public class RequestCorrelationFilterTest {
48 |
49 | private RequestCorrelationFilter instance;
50 |
51 | private CorrelationIdGenerator generator = new UuidGenerator();
52 |
53 | private List interceptors = new ArrayList<>();
54 |
55 | private RequestCorrelationProperties properties = new RequestCorrelationProperties();
56 |
57 | @Before
58 | public void setUp() throws Exception {
59 |
60 | instance = new RequestCorrelationFilter(generator, interceptors, properties);
61 | }
62 |
63 | @Test
64 | public void shouldInitiateCorrelationId() throws IOException, ServletException {
65 |
66 | // given
67 | final MockHttpServletRequest request = new MockHttpServletRequest();
68 | final MockHttpServletResponse response = new MockHttpServletResponse();
69 | final MockFilterChain chain = new MockFilterChain();
70 |
71 | // when
72 | instance.doFilter(request, response, chain);
73 |
74 | // then
75 | assertNotNull(request.getAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME));
76 | assertNotNull(((HttpServletRequest)chain.getRequest()).getHeader(RequestCorrelationConsts.HEADER_NAME));
77 | }
78 |
79 | @Test
80 | public void shouldUseExistingCorrelationId() throws IOException, ServletException {
81 |
82 | // given
83 | final String requestId = UUID.randomUUID().toString();
84 | final MockHttpServletRequest request = new MockHttpServletRequest();
85 | final MockHttpServletResponse response = new MockHttpServletResponse();
86 | final MockFilterChain chain = new MockFilterChain();
87 |
88 | request.addHeader(RequestCorrelationConsts.HEADER_NAME, requestId);
89 |
90 | // when
91 | instance.doFilter(request, response, chain);
92 |
93 | // then
94 | final Object requestCorrelation = request.getAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME);
95 | assertNotNull(requestCorrelation);
96 | assertEquals(requestId, ((RequestCorrelation) requestCorrelation).getRequestId());
97 |
98 | final String header = ((HttpServletRequest) chain.getRequest()).getHeader(RequestCorrelationConsts.HEADER_NAME);
99 | assertNotNull(header);
100 | assertEquals(requestId, header);
101 | }
102 |
103 | @Test
104 | public void shouldUseCustomHeader() throws IOException, ServletException {
105 |
106 | // given
107 | final String headerName = "X-TraceId";
108 | final String requestId = UUID.randomUUID().toString();
109 | final MockHttpServletRequest request = new MockHttpServletRequest();
110 | final MockHttpServletResponse response = new MockHttpServletResponse();
111 | final MockFilterChain chain = new MockFilterChain();
112 |
113 | request.addHeader(headerName, requestId);
114 | properties.setHeaderName(headerName);
115 |
116 | // when
117 | instance.doFilter(request, response, chain);
118 |
119 | // then
120 | final Object requestCorrelation = request.getAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME);
121 | assertNotNull(requestCorrelation);
122 | assertEquals(requestId, ((RequestCorrelation) requestCorrelation).getRequestId());
123 |
124 | final String header = ((HttpServletRequest) chain.getRequest()).getHeader(headerName);
125 | assertNotNull(header);
126 | assertEquals(requestId, header);
127 | }
128 |
129 | @Test
130 | public void shouldInvokeInterceptor() throws IOException, ServletException {
131 |
132 | // given
133 | final MockHttpServletRequest request = new MockHttpServletRequest();
134 | final MockHttpServletResponse response = new MockHttpServletResponse();
135 | final MockFilterChain chain = new MockFilterChain();
136 |
137 | final RequestCorrelationInterceptor interceptor = mock(RequestCorrelationInterceptor.class);
138 | interceptors.add(interceptor);
139 |
140 | // when
141 | instance.doFilter(request, response, chain);
142 |
143 | // then
144 | final String requestId = ((HttpServletRequest) chain.getRequest()).getHeader(RequestCorrelationConsts.HEADER_NAME);
145 | final RequestCorrelation correlationId = (RequestCorrelation) request.getAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME);
146 | assertNotNull(requestId);
147 | assertNotNull(correlationId);
148 | assertEquals(requestId, correlationId.getRequestId());
149 |
150 | verify(interceptor).afterCorrelationIdSet(requestId);
151 | verify(interceptor).cleanUp(requestId);
152 | }
153 | }
--------------------------------------------------------------------------------
/src/test/java/io/jmnarloch/spring/request/correlation/generator/UuidGeneratorTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.generator;
17 |
18 | import org.junit.Test;
19 |
20 | import static org.junit.Assert.assertNotNull;
21 |
22 | /**
23 | * Tests the {@link UuidGenerator} class.
24 | *
25 | * @author Jakub Narloch
26 | */
27 | public class UuidGeneratorTest {
28 |
29 | @Test
30 | public void shouldGenerateId() {
31 |
32 | // when
33 | final String requestId = new UuidGenerator().generate();
34 |
35 | // then
36 | assertNotNull(requestId);
37 | }
38 |
39 | }
--------------------------------------------------------------------------------
/src/test/java/io/jmnarloch/spring/request/correlation/http/ClientHttpRequestCorrelationInterceptorTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.http;
17 |
18 | import io.jmnarloch.spring.request.correlation.CorrelationTestUtils;
19 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationConsts;
20 | import io.jmnarloch.spring.request.correlation.support.RequestCorrelationProperties;
21 | import org.junit.After;
22 | import org.junit.Before;
23 | import org.junit.Test;
24 | import org.springframework.http.HttpHeaders;
25 | import org.springframework.http.HttpRequest;
26 | import org.springframework.http.client.ClientHttpRequestExecution;
27 | import org.springframework.mock.web.MockHttpServletRequest;
28 | import org.springframework.web.context.request.RequestContextHolder;
29 | import org.springframework.web.context.request.ServletRequestAttributes;
30 |
31 | import java.io.IOException;
32 | import java.util.UUID;
33 |
34 | import static org.junit.Assert.*;
35 | import static org.mockito.Mockito.*;
36 |
37 | /**
38 | * Tests the {@link ClientHttpRequestCorrelationInterceptor} class.
39 | *
40 | * @author Jakub Narloch
41 | */
42 | public class ClientHttpRequestCorrelationInterceptorTest {
43 |
44 | private ClientHttpRequestCorrelationInterceptor instance;
45 |
46 | @Before
47 | public void setUp() throws Exception {
48 | instance = new ClientHttpRequestCorrelationInterceptor(new RequestCorrelationProperties());
49 |
50 | RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
51 | }
52 |
53 | @After
54 | public void tearDown() throws Exception {
55 |
56 | RequestContextHolder.resetRequestAttributes();
57 | }
58 |
59 | @Test
60 | public void shouldSetHeader() throws IOException {
61 |
62 | // given
63 | final String requestId = UUID.randomUUID().toString();
64 | CorrelationTestUtils.setRequestId(requestId);
65 |
66 | final HttpRequest request = mock(HttpRequest.class);
67 | final ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
68 | final byte[] body = new byte[0];
69 |
70 | when(request.getHeaders()).thenReturn(new HttpHeaders());
71 |
72 | // when
73 | instance.intercept(request, body, execution);
74 |
75 | // then
76 | assertTrue(request.getHeaders().containsKey(RequestCorrelationConsts.HEADER_NAME));
77 | assertEquals(requestId, request.getHeaders().getFirst(RequestCorrelationConsts.HEADER_NAME));
78 | verify(execution).execute(request, body);
79 | }
80 |
81 | @Test
82 | public void shouldNotSetHeader() throws IOException {
83 |
84 | // given
85 | final HttpRequest request = mock(HttpRequest.class);
86 | final ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
87 | final byte[] body = new byte[0];
88 |
89 | when(request.getHeaders()).thenReturn(new HttpHeaders());
90 |
91 | // when
92 | instance.intercept(request, body, execution);
93 |
94 | // then
95 | assertFalse(request.getHeaders().containsKey(RequestCorrelationConsts.HEADER_NAME));
96 | verify(execution).execute(request, body);
97 | }
98 | }
--------------------------------------------------------------------------------
/src/test/java/io/jmnarloch/spring/request/correlation/support/RequestCorrelationUtilsTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 the original author or authors
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.jmnarloch.spring.request.correlation.support;
17 |
18 | import io.jmnarloch.spring.request.correlation.filter.DefaultRequestCorrelation;
19 | import org.junit.After;
20 | import org.junit.Before;
21 | import org.junit.Test;
22 | import org.springframework.mock.web.MockHttpServletRequest;
23 | import org.springframework.web.context.request.RequestAttributes;
24 | import org.springframework.web.context.request.RequestContextHolder;
25 | import org.springframework.web.context.request.ServletRequestAttributes;
26 |
27 | import java.util.UUID;
28 |
29 | import static org.junit.Assert.assertEquals;
30 | import static org.junit.Assert.assertNull;
31 |
32 | /**
33 | * Tests the {@link RequestCorrelationUtils} class.
34 | *
35 | * @author Jakub Narloch
36 | */
37 | public class RequestCorrelationUtilsTest {
38 |
39 | @Before
40 | public void setUp() throws Exception {
41 |
42 | RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
43 | }
44 |
45 | @After
46 | public void tearDown() throws Exception {
47 |
48 | RequestContextHolder.resetRequestAttributes();
49 | }
50 |
51 | @Test
52 | public void shouldNotRetrieveRequestId() {
53 |
54 | // given
55 | RequestContextHolder.resetRequestAttributes();
56 |
57 | // when
58 | final String correlationId = RequestCorrelationUtils.getCurrentCorrelationId();
59 |
60 | // then
61 | assertNull(correlationId);
62 | }
63 |
64 | @Test
65 | public void shouldRetrieveRequestId() {
66 |
67 | // given
68 | final String requestId = UUID.randomUUID().toString();
69 | RequestContextHolder.getRequestAttributes().setAttribute(RequestCorrelationConsts.ATTRIBUTE_NAME,
70 | new DefaultRequestCorrelation(requestId), RequestAttributes.SCOPE_REQUEST);
71 |
72 | // when
73 | final String correlationId = RequestCorrelationUtils.getCurrentCorrelationId();
74 |
75 | // then
76 | assertEquals(requestId, correlationId);
77 | }
78 | }
--------------------------------------------------------------------------------
/src/test/resources/application.yml:
--------------------------------------------------------------------------------
1 | request.correlation.header-name=X-Request-Id
2 | request.correlation.client.http.enable=true
3 | request.correlation.client.feign.enable=true
--------------------------------------------------------------------------------