forked from dbacinski/Design-Patterns-In-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChainOfResponsibility.kt
80 lines (62 loc) · 2.3 KB
/
ChainOfResponsibility.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
interface HeadersChain {
fun addHeader(inputHeader: String): String
}
class AuthenticationHeader(val token: String?, var next: HeadersChain? = null) : HeadersChain {
override fun addHeader(inputHeader: String): String {
token ?: throw IllegalStateException("Token should be not null")
return inputHeader + "Authorization: Bearer $token\n"
.let { next?.addHeader(it) ?: it }
}
}
class ContentTypeHeader(val contentType: String, var next: HeadersChain? = null) : HeadersChain {
override fun addHeader(inputHeader: String): String =
inputHeader + "ContentType: $contentType\n"
.let { next?.addHeader(it) ?: it }
}
class BodyPayload(val body: String, var next: HeadersChain? = null) : HeadersChain {
override fun addHeader(inputHeader: String): String =
inputHeader + "$body"
.let { next?.addHeader(it) ?: it }
}
class ChainOfResponsibilityTest {
@Test
fun `Chain Of Responsibility`() {
//create chain elements
val authenticationHeader = AuthenticationHeader("123456")
val contentTypeHeader = ContentTypeHeader("json")
val messageBody = BodyPayload("Body:\n{\n\"username\"=\"dbacinski\"\n}")
//construct chain
authenticationHeader.next = contentTypeHeader
contentTypeHeader.next = messageBody
//execute chain
val messageWithAuthentication =
authenticationHeader.addHeader("Headers with Authentication:\n")
println(messageWithAuthentication)
val messageWithoutAuth =
contentTypeHeader.addHeader("Headers:\n")
println(messageWithoutAuth)
assertThat(messageWithAuthentication).isEqualTo(
"""
Headers with Authentication:
Authorization: Bearer 123456
ContentType: json
Body:
{
"username"="dbacinski"
}
""".trimIndent()
)
assertThat(messageWithoutAuth).isEqualTo(
"""
Headers:
ContentType: json
Body:
{
"username"="dbacinski"
}
""".trimIndent()
)
}
}