/
WiretapConnector.java
271 lines (207 loc) · 8.05 KB
/
WiretapConnector.java
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.reactive.server;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoProcessor;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ClientHttpRequest;
import org.springframework.http.client.reactive.ClientHttpRequestDecorator;
import org.springframework.http.client.reactive.ClientHttpResponse;
import org.springframework.http.client.reactive.ClientHttpResponseDecorator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Decorate another {@link ClientHttpConnector} with the purpose of
* intercepting, capturing, and exposing actual request and response data
* transmitted to and received from the server.
*
* @author Rossen Stoyanchev
* @since 5.0
* @see HttpHandlerConnector
*/
class WiretapConnector implements ClientHttpConnector {
private final ClientHttpConnector delegate;
private final Map<String, Info> exchanges = new ConcurrentHashMap<>();
WiretapConnector(ClientHttpConnector delegate) {
this.delegate = delegate;
}
@Override
public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri,
Function<? super ClientHttpRequest, Mono<Void>> requestCallback) {
AtomicReference<WiretapClientHttpRequest> requestRef = new AtomicReference<>();
return this.delegate
.connect(method, uri, request -> {
WiretapClientHttpRequest wrapped = new WiretapClientHttpRequest(request);
requestRef.set(wrapped);
return requestCallback.apply(wrapped);
})
.map(response -> {
WiretapClientHttpRequest wrappedRequest = requestRef.get();
String header = WebTestClient.WEBTESTCLIENT_REQUEST_ID;
String requestId = wrappedRequest.getHeaders().getFirst(header);
Assert.state(requestId != null, () -> "No \"" + header + "\" header");
WiretapClientHttpResponse wrappedResponse = new WiretapClientHttpResponse(response);
this.exchanges.put(requestId, new Info(wrappedRequest, wrappedResponse));
return wrappedResponse;
});
}
/**
* Retrieve the {@link Info} for the given "request-id" header value.
*/
public Info claimRequest(String requestId) {
Info info = this.exchanges.remove(requestId);
Assert.state(info != null, () -> {
String header = WebTestClient.WEBTESTCLIENT_REQUEST_ID;
return "No match for " + header + "=" + requestId;
});
return info;
}
/**
* Holder for {@link WiretapClientHttpRequest} and {@link WiretapClientHttpResponse}.
*/
class Info {
private final WiretapClientHttpRequest request;
private final WiretapClientHttpResponse response;
public Info(WiretapClientHttpRequest request, WiretapClientHttpResponse response) {
this.request = request;
this.response = response;
}
public ExchangeResult createExchangeResult(@Nullable String uriTemplate) {
return new ExchangeResult(this.request, this.response,
this.request.getRecorder().getContent(), this.response.getRecorder().getContent(), uriTemplate);
}
}
/**
* Tap into a Publisher of data buffers to save the content.
*/
final static class WiretapRecorder {
private static final DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
public static final byte[] EMPTY_CONTENT = new byte[0];
@Nullable
private final Publisher<? extends DataBuffer> publisher;
@Nullable
private final Publisher<? extends Publisher<? extends DataBuffer>> publisherNested;
private final DataBuffer buffer;
private final MonoProcessor<byte[]> content;
private WiretapRecorder(@Nullable Publisher<? extends DataBuffer> publisher,
@Nullable Publisher<? extends Publisher<? extends DataBuffer>> publisherNested) {
if (publisher != null && publisherNested != null) {
throw new IllegalArgumentException("At most one publisher expected");
}
this.publisher = publisher != null ?
Flux.from(publisher)
.doOnNext(this::handleOnNext)
.doOnError(this::handleOnError)
.doOnCancel(this::handleOnComplete)
.doOnComplete(this::handleOnComplete) : null;
this.publisherNested = publisherNested != null ?
Flux.from(publisherNested)
.map(p -> Flux.from(p).doOnNext(this::handleOnNext).doOnError(this::handleOnError))
.doOnError(this::handleOnError)
.doOnCancel(this::handleOnComplete)
.doOnComplete(this::handleOnComplete) : null;
this.buffer = bufferFactory.allocateBuffer();
this.content = MonoProcessor.create();
if (this.publisher == null && this.publisherNested == null) {
this.content.onNext(EMPTY_CONTENT);
}
}
public Publisher<? extends DataBuffer> getPublisherToUse() {
Assert.notNull(this.publisher, "Publisher not in use.");
return this.publisher;
}
public Publisher<? extends Publisher<? extends DataBuffer>> getNestedPublisherToUse() {
Assert.notNull(this.publisherNested, "Nested publisher not in use.");
return this.publisherNested;
}
public MonoProcessor<byte[]> getContent() {
return this.content;
}
private void handleOnNext(DataBuffer nextBuffer) {
this.buffer.write(nextBuffer);
}
private void handleOnError(Throwable ex) {
if (!this.content.isTerminated()) {
this.content.onError(ex);
}
}
private void handleOnComplete() {
if (!this.content.isTerminated()) {
byte[] bytes = new byte[this.buffer.readableByteCount()];
this.buffer.read(bytes);
this.content.onNext(bytes);
}
}
}
/**
* ClientHttpRequestDecorator that intercepts and saves the request body.
*/
private static class WiretapClientHttpRequest extends ClientHttpRequestDecorator {
@Nullable
private WiretapRecorder recorder;
public WiretapClientHttpRequest(ClientHttpRequest delegate) {
super(delegate);
}
public WiretapRecorder getRecorder() {
Assert.notNull(this.recorder, "No WiretapRecorder: was the client request written?");
return this.recorder;
}
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> publisher) {
this.recorder = new WiretapRecorder(publisher, null);
return super.writeWith(this.recorder.getPublisherToUse());
}
@Override
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> publisher) {
this.recorder = new WiretapRecorder(null, publisher);
return super.writeAndFlushWith(this.recorder.getNestedPublisherToUse());
}
@Override
public Mono<Void> setComplete() {
this.recorder = new WiretapRecorder(null, null);
return super.setComplete();
}
}
/**
* ClientHttpResponseDecorator that intercepts and saves the response body.
*/
private static class WiretapClientHttpResponse extends ClientHttpResponseDecorator {
private final WiretapRecorder recorder;
public WiretapClientHttpResponse(ClientHttpResponse delegate) {
super(delegate);
this.recorder = new WiretapRecorder(super.getBody(), null);
}
public WiretapRecorder getRecorder() {
return this.recorder;
}
@Override
@SuppressWarnings("ConstantConditions")
public Flux<DataBuffer> getBody() {
return Flux.from(this.recorder.getPublisherToUse());
}
}
}