1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package io.wcm.caravan.testing.http;
21
22 import io.wcm.caravan.io.http.response.CaravanHttpResponse;
23 import io.wcm.caravan.io.http.response.CaravanHttpResponseBuilder;
24
25 import java.util.regex.Pattern;
26
27 import org.apache.commons.lang3.StringUtils;
28 import org.hamcrest.BaseMatcher;
29 import org.hamcrest.Description;
30 import org.hamcrest.Matcher;
31 import org.hamcrest.core.IsEqual;
32 import org.hamcrest.core.StringStartsWith;
33 import org.osgi.annotation.versioning.ProviderType;
34
35 import com.google.common.base.Charsets;
36
37
38
39
40
41 @ProviderType
42 public final class RequestMatcher {
43
44 private String serviceId;
45 private Matcher<String> urlMatcher;
46 private CaravanHttpResponse response;
47
48
49
50
51
52 public RequestMatcher serviceId(String value) {
53 this.serviceId = value;
54 return this;
55 }
56
57
58
59
60
61
62 @Deprecated
63 public RequestMatcher serviceName(String value) {
64 return serviceId(value);
65 }
66
67
68
69
70
71 public RequestMatcher url(String value) {
72 this.urlMatcher = IsEqual.<String>equalTo(value);
73 return this;
74 }
75
76
77
78
79
80 public RequestMatcher urlStartsWith(String value) {
81 this.urlMatcher = StringStartsWith.startsWith(value);
82 return this;
83 }
84
85
86
87
88
89 public RequestMatcher urlMatches(Matcher<String> value) {
90 this.urlMatcher = value;
91 return this;
92 }
93
94
95
96
97
98 public RequestMatcher urlMatches(final Pattern pattern) {
99 this.urlMatcher = new BaseMatcher<String>() {
100 @Override
101 public boolean matches(Object item) {
102 return pattern.matcher(item.toString()).matches();
103 }
104 @Override
105 public void describeTo(Description description) {
106 description.appendText("Pattern " + pattern.toString());
107 }
108 };
109 return this;
110 }
111
112
113
114
115
116 public void response(String payload) {
117 response(toResponse(payload));
118 }
119
120
121
122
123
124 public void response(CaravanHttpResponse payload) {
125 this.response = payload;
126 }
127
128 boolean matches(String expectedServiceId, String expectedUrl) {
129 return (this.serviceId == null || StringUtils.equals(expectedServiceId, this.serviceId))
130 && (this.urlMatcher == null || urlMatcher.matches(expectedUrl))
131 && (response != null);
132 }
133
134 CaravanHttpResponse getResponse() {
135 return response;
136 }
137
138 private static CaravanHttpResponse toResponse(String payload) {
139 return new CaravanHttpResponseBuilder()
140 .status(200)
141 .reason("OK")
142 .body(payload.toString(), Charsets.UTF_8)
143 .build();
144 }
145
146 }