org.springframework.http.client.reactive.ClientHttpRequest Java Examples

The following examples show how to use org.springframework.http.client.reactive.ClientHttpRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BodyInserterRequestBuilderWriteToInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);

    if (!validate(args)) {
        return;
    }

    final ClientHttpRequest request = (ClientHttpRequest) args[0];
    final ClientRequestWrapper clientRequestWrapper = new WebClientRequestWrapper(request);
    this.clientRequestRecorder.record(recorder, clientRequestWrapper, throwable);
    this.cookieRecorder.record(recorder, request, throwable);

    if (isAsync(result)) {
        // make asynchronous trace-id
        final AsyncContext asyncContext = recorder.recordNextAsyncContext();
        ((AsyncContextAccessor) result)._$PINPOINT$_setAsyncContext(asyncContext);
        if (isDebug) {
            logger.debug("Set closeable-AsyncContext {}", asyncContext);
        }
    }
}
 
Example #2
Source File: BodyInsertersTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void fromFormDataWith() {
	BodyInserter<MultiValueMap<String, String>, ClientHttpRequest>
			inserter = BodyInserters.fromFormData("name 1", "value 1")
			.with("name 2", "value 2+1")
			.with("name 2", "value 2+2")
			.with("name 3", null);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("http://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

	StepVerifier.create(request.getBody())
			.consumeNextWith(dataBuffer -> {
				byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(resultBytes);
				DataBufferUtils.release(dataBuffer);
				assertArrayEquals("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8),
						resultBytes);
			})
			.expectComplete()
			.verify();

}
 
Example #3
Source File: WiretapConnector.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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;
			});
}
 
Example #4
Source File: ExchangeResult.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create an instance with an HTTP request and response along with promises
 * for the serialized request and response body content.
 *
 * @param request the HTTP request
 * @param response the HTTP response
 * @param requestBody capture of serialized request body content
 * @param responseBody capture of serialized response body content
 * @param timeout how long to wait for content to materialize
 * @param uriTemplate the URI template used to set up the request, if any
 */
ExchangeResult(ClientHttpRequest request, ClientHttpResponse response,
		Mono<byte[]> requestBody, Mono<byte[]> responseBody, Duration timeout, @Nullable String uriTemplate) {

	Assert.notNull(request, "ClientHttpRequest is required");
	Assert.notNull(response, "ClientHttpResponse is required");
	Assert.notNull(requestBody, "'requestBody' is required");
	Assert.notNull(responseBody, "'responseBody' is required");

	this.request = request;
	this.response = response;
	this.requestBody = requestBody;
	this.responseBody = responseBody;
	this.timeout = timeout;
	this.uriTemplate = uriTemplate;
}
 
Example #5
Source File: WiretapConnectorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void captureAndClaim() {
	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, "/test");
	ClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
			.header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build();

	WiretapConnector wiretapConnector = new WiretapConnector(connector);
	ExchangeFunction function = ExchangeFunctions.create(wiretapConnector);
	function.exchange(clientRequest).block(ofMillis(0));

	WiretapConnector.Info actual = wiretapConnector.claimRequest("1");
	ExchangeResult result = actual.createExchangeResult(Duration.ZERO, null);
	assertEquals(HttpMethod.GET, result.getMethod());
	assertEquals("/test", result.getUrl().toString());
}
 
Example #6
Source File: VertxClientHttpConnector.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<ClientHttpResponse> connect(org.springframework.http.HttpMethod method, URI uri,
    Function<? super ClientHttpRequest, Mono<Void>> requestCallback) {

    logger.debug("Connecting to '{}' with '{}", uri, method);

    if (!uri.isAbsolute()) {
        return Mono.error(new IllegalArgumentException("URI is not absolute: " + uri));
    }

    CompletableFuture<ClientHttpResponse> responseFuture = new CompletableFuture<>();
    HttpClient client = vertx.createHttpClient(clientOptions);
    HttpClientRequest request = client.requestAbs(HttpMethod.valueOf(method.name()), uri.toString())
        .exceptionHandler(responseFuture::completeExceptionally)
        .handler(response -> {
            Flux<DataBuffer> responseBody = responseToFlux(response)
                .doFinally(ignore -> client.close());

            responseFuture.complete(new VertxClientHttpResponse(response, responseBody));
        });

    return requestCallback.apply(new VertxClientHttpRequest(request, bufferConverter))
        .then(Mono.fromCompletionStage(responseFuture));
}
 
Example #7
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Select the body to use for the request
 * @param obj the body object
 * @param formParams the form parameters
 * @param contentType the content type of the request
 * @return Object the selected body
 */
protected BodyInserter<?, ? super ClientHttpRequest> selectBody(Object obj, MultiValueMap<String, Object> formParams, MediaType contentType) {
    if(MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap();

        formParams
                .toSingleValueMap()
                .entrySet()
                .forEach(es -> map.add(es.getKey(), String.valueOf(es.getValue())));

        return BodyInserters.fromFormData(map);
    } else if(MediaType.MULTIPART_FORM_DATA.equals(contentType)) {
        return BodyInserters.fromMultipartData(formParams);
    } else {
        return obj != null ? BodyInserters.fromObject(obj) : null;
    }
}
 
Example #8
Source File: ExchangeResult.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create an instance with an HTTP request and response along with promises
 * for the serialized request and response body content.
 *
 * @param request the HTTP request
 * @param response the HTTP response
 * @param requestBody capture of serialized request body content
 * @param responseBody capture of serialized response body content
 * @param timeout how long to wait for content to materialize
 * @param uriTemplate the URI template used to set up the request, if any
 */
ExchangeResult(ClientHttpRequest request, ClientHttpResponse response,
		Mono<byte[]> requestBody, Mono<byte[]> responseBody, Duration timeout, @Nullable String uriTemplate) {

	Assert.notNull(request, "ClientHttpRequest is required");
	Assert.notNull(response, "ClientHttpResponse is required");
	Assert.notNull(requestBody, "'requestBody' is required");
	Assert.notNull(responseBody, "'responseBody' is required");

	this.request = request;
	this.response = response;
	this.requestBody = requestBody;
	this.responseBody = responseBody;
	this.timeout = timeout;
	this.uriTemplate = uriTemplate;
}
 
Example #9
Source File: AuthenticationStepsOperatorUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void justLoginRequestShouldLogin() {

	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/cert/login");
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
	response.setBody(
			"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}");
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	WebClient webClient = WebClient.builder().clientConnector(connector).build();

	AuthenticationSteps steps = AuthenticationSteps
			.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));

	login(steps, webClient).as(StepVerifier::create) //
			.expectNext(VaultToken.of("my-token")) //
			.verifyComplete();
}
 
Example #10
Source File: AuthenticationStepsOperatorUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void justLoginShouldFail() {

	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/cert/login");
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.BAD_REQUEST);
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	WebClient webClient = WebClient.builder().clientConnector(connector).build();

	AuthenticationSteps steps = AuthenticationSteps
			.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));

	login(steps, webClient).as(StepVerifier::create) //
			.expectError() //
			.verify();
}
 
Example #11
Source File: WiretapConnector.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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;
			});
}
 
Example #12
Source File: BodyInsertersTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void fromFormDataWith() {
	BodyInserter<MultiValueMap<String, String>, ClientHttpRequest>
			inserter = BodyInserters.fromFormData("name 1", "value 1")
			.with("name 2", "value 2+1")
			.with("name 2", "value 2+2")
			.with("name 3", null);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("https://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

	StepVerifier.create(request.getBody())
			.consumeNextWith(dataBuffer -> {
				byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(resultBytes);
				DataBufferUtils.release(dataBuffer);
				assertArrayEquals("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8),
						resultBytes);
			})
			.expectComplete()
			.verify();

}
 
Example #13
Source File: ReactiveVaultClientsUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldApplyNamespace() {

	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/foo");
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);

	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	WebClient webClient = WebClient.builder().clientConnector(connector)
			.filter(ReactiveVaultClients.namespace("foo/bar")).build();

	webClient.get().uri("/auth/foo").retrieve().bodyToMono(String.class).as(StepVerifier::create) //
			.verifyComplete();

	assertThat(request.getHeaders()).containsEntry(VaultHttpHeaders.VAULT_NAMESPACE,
			Collections.singletonList("foo/bar"));
}
 
Example #14
Source File: ReactiveVaultClientsUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldAllowNamespaceOverride() {

	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/foo");
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);

	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	WebClient webClient = WebClient.builder().clientConnector(connector)
			.filter(ReactiveVaultClients.namespace("foo/bar")).build();

	webClient.get().uri("/auth/foo").header(VaultHttpHeaders.VAULT_NAMESPACE, "baz").retrieve()
			.bodyToMono(String.class) //
			.as(StepVerifier::create) //
			.verifyComplete();

	assertThat(request.getHeaders()).containsEntry(VaultHttpHeaders.VAULT_NAMESPACE,
			Collections.singletonList("baz"));
}
 
Example #15
Source File: ArmeriaClientHttpConnector.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<ClientHttpResponse> connect(
        HttpMethod method, URI uri, Function<? super ClientHttpRequest, Mono<Void>> requestCallback) {
    try {
        requireNonNull(method, "method");
        requireNonNull(uri, "uri");
        requireNonNull(requestCallback, "requestCallback");

        final ArmeriaClientHttpRequest request = createRequest(method, uri);
        return requestCallback.apply(request)
                              .then(Mono.fromFuture(request.future()))
                              .map(ArmeriaHttpClientResponseSubscriber::new)
                              .flatMap(s -> Mono.fromFuture(s.headersFuture())
                                                .map(headers -> createResponse(headers, s)));
    } catch (NullPointerException | IllegalArgumentException e) {
        return Mono.error(e);
    }
}
 
Example #16
Source File: InstanceWebProxy.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
public Mono<ClientResponse> forward(Instance instance, URI uri, HttpMethod method, HttpHeaders headers,
		BodyInserter<?, ? super ClientHttpRequest> bodyInserter) {
	log.trace("Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
	WebClient.RequestBodySpec bodySpec = this.instanceWebClient.instance(instance).method(method).uri(uri)
			.headers((h) -> h.addAll(headers));

	WebClient.RequestHeadersSpec<?> headersSpec = bodySpec;
	if (requiresBody(method)) {
		headersSpec = bodySpec.body(bodyInserter);
	}

	return headersSpec.exchange()
			.onErrorResume((ex) -> ex instanceof ReadTimeoutException || ex instanceof TimeoutException,
					(ex) -> Mono.fromSupplier(() -> {
						log.trace("Timeout for Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
						return ClientResponse.create(HttpStatus.GATEWAY_TIMEOUT, this.strategies).build();
					}))
			.onErrorResume(ResolveEndpointException.class, (ex) -> Mono.fromSupplier(() -> {
				log.trace("No Endpoint found for Proxy-Request for instance {} with URL '{}'", instance.getId(),
						uri);
				return ClientResponse.create(HttpStatus.NOT_FOUND, this.strategies).build();
			})).onErrorResume(IOException.class, (ex) -> Mono.fromSupplier(() -> {
				log.trace("Proxy-Request for instance {} with URL '{}' errored", instance.getId(), uri, ex);
				return ClientResponse.create(HttpStatus.BAD_GATEWAY, this.strategies).build();
			}));
}
 
Example #17
Source File: ClientHttpRequestCookieExtractor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public String getCookie(final ClientHttpRequest request) {
    if (request != null && request.getCookies() != null) {
        final StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, List<HttpCookie>> entry : request.getCookies().entrySet()) {
            boolean repeated = false;
            for (HttpCookie httpCookie : entry.getValue()) {
                if (repeated) {
                    sb.append(',');
                }
                sb.append(httpCookie.getName());
                sb.append('=');
                sb.append(httpCookie.getValue());
                repeated = true;
            }
        }
        if (isDebug) {
            logger.debug("Cookie={}", sb.toString());
        }
        return sb.toString();
    }
    return null;
}
 
Example #18
Source File: BodyInserterRequestBuilderWriteToInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncContext, Object target, Object[] args) {
    if (!validate(args)) {
        return;
    }

    final ClientHttpRequest request = (ClientHttpRequest) args[0];
    final Trace trace = asyncContext.currentAsyncTraceObject();
    if (trace == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Unexpected error, Current async trace is null");
        }
        return;
    }
    final TraceId nextId = trace.getTraceId().getNextTraceId();
    recorder.recordNextSpanId(nextId.getSpanId());
    recorder.recordServiceType(SpringWebFluxConstants.SPRING_WEBFLUX_CLIENT);

    final URI url = request.getURI();
    String host = null;
    if (url != null) {
        host = HostAndPort.toHostAndPortString(url.getHost(), url.getPort());
    }
    requestTraceWriter.write(request, nextId, host);
}
 
Example #19
Source File: BodyInserterRequestBuilderWriteToInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private boolean validate(final Object[] args) {
    if (args == null || args.length < 1) {
        if (isDebug) {
            logger.debug("Invalid args object. args={}.", args);
        }
        return false;
    }

    if (!(args[0] instanceof ClientHttpRequest)) {
        if (isDebug) {
            logger.debug("Invalid args[0] object. Need ClientHttpRequest, args[0]={}.", args[0]);
        }
        return false;
    }

    return true;
}
 
Example #20
Source File: AbstractInstancesProxyController.java    From Moss with Apache License 2.0 5 votes vote down vote up
protected Mono<ClientResponse> forward(String instanceId,
                                       URI uri,
                                       HttpMethod method,
                                       HttpHeaders headers,
                                       Supplier<BodyInserter<?, ? super ClientHttpRequest>> bodyInserter) {
    log.trace("Proxy-Request for instance {} with URL '{}'", instanceId, uri);

    return registry.getInstance(InstanceId.of(instanceId))
                   .flatMap(instance -> forward(instance, uri, method, headers, bodyInserter))
                   .switchIfEmpty(Mono.fromSupplier(() -> ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE, strategies).build()));
}
 
Example #21
Source File: AuthenticationStepsOperatorUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void zipWithShouldRequestTwoItems() {

	ClientHttpRequest leftRequest = new MockClientHttpRequest(HttpMethod.GET, "/auth/login/left");
	MockClientHttpResponse leftResponse = new MockClientHttpResponse(HttpStatus.OK);
	leftResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
	leftResponse.setBody("{" + "\"request_id\": \"left\"}");

	ClientHttpRequest rightRequest = new MockClientHttpRequest(HttpMethod.GET, "/auth/login/right");
	MockClientHttpResponse rightResponse = new MockClientHttpResponse(HttpStatus.OK);
	rightResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
	rightResponse.setBody("{" + "\"request_id\": \"right\"}");

	ClientHttpConnector connector = (method, uri, fn) -> {

		if (uri.toString().contains("left")) {
			return fn.apply(leftRequest).then(Mono.just(leftResponse));
		}

		return fn.apply(rightRequest).then(Mono.just(rightResponse));
	};

	WebClient webClient = WebClient.builder().clientConnector(connector).build();

	Node<VaultResponse> left = AuthenticationSteps
			.fromHttpRequest(post("/auth/login/left").as(VaultResponse.class));

	Node<VaultResponse> right = AuthenticationSteps
			.fromHttpRequest(post("/auth/login/right").as(VaultResponse.class));

	AuthenticationSteps steps = left.zipWith(right)
			.login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId()));

	login(steps, webClient).as(StepVerifier::create) //
			.expectNext(VaultToken.of("left-right")) //
			.verifyComplete();
}
 
Example #22
Source File: AbstractInstancesProxyController.java    From Moss with Apache License 2.0 5 votes vote down vote up
private Mono<ClientResponse> forward(Instance instance,
                                     URI uri,
                                     HttpMethod method,
                                     HttpHeaders headers,
                                     Supplier<BodyInserter<?, ? super ClientHttpRequest>> bodyInserter) {
    WebClient.RequestBodySpec bodySpec = instanceWebClient.instance(instance)
                                                          .method(method)
                                                          .uri(uri)
                                                          .headers(h -> h.addAll(filterHeaders(headers)));

    WebClient.RequestHeadersSpec<?> headersSpec = bodySpec;
    if (requiresBody(method)) {
        try {
            headersSpec = bodySpec.body(bodyInserter.get());
        } catch (Exception ex) {
            return Mono.error(ex);
        }
    }

    return headersSpec.exchange().onErrorResume(ReadTimeoutException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("Timeout for Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
        return ClientResponse.create(HttpStatus.GATEWAY_TIMEOUT, strategies).build();
    })).onErrorResume(ResolveEndpointException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("No Endpoint found for Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
        return ClientResponse.create(HttpStatus.NOT_FOUND, strategies).build();
    })).onErrorResume(IOException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("Proxy-Request for instance {} with URL '{}' errored", instance.getId(), uri, ex);
        return ClientResponse.create(HttpStatus.BAD_GATEWAY, strategies).build();
    })).onErrorResume(ConnectException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("Connect for Proxy-Request for instance {} with URL '{}' failed", instance.getId(), uri, ex);
        return ClientResponse.create(HttpStatus.BAD_GATEWAY, strategies).build();
    }));
}
 
Example #23
Source File: BodyInserters.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> insert(ClientHttpRequest outputMessage, Context context) {
	HttpMessageWriter<MultiValueMap<String, String>> messageWriter =
			findWriter(context, FORM_DATA_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
	return messageWriter.write(Mono.just(this.data), FORM_DATA_TYPE,
			MediaType.APPLICATION_FORM_URLENCODED,
			outputMessage, context.hints());
}
 
Example #24
Source File: DefaultClientRequestBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> writeTo(ClientHttpRequest request, ExchangeStrategies strategies) {
	HttpHeaders requestHeaders = request.getHeaders();
	if (!this.headers.isEmpty()) {
		this.headers.entrySet().stream()
				.filter(entry -> !requestHeaders.containsKey(entry.getKey()))
				.forEach(entry -> requestHeaders
						.put(entry.getKey(), entry.getValue()));
	}

	MultiValueMap<String, HttpCookie> requestCookies = request.getCookies();
	if (!this.cookies.isEmpty()) {
		this.cookies.forEach((name, values) -> values.forEach(value -> {
			HttpCookie cookie = new HttpCookie(name, value);
			requestCookies.add(name, cookie);
		}));
	}

	return this.body.insert(request, new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return strategies.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.empty();
		}
		@Override
		public Map<String, Object> hints() {
			return Hints.from(Hints.LOG_PREFIX_HINT, logPrefix());
		}
	});
}
 
Example #25
Source File: BodyInsertersTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void fromFormDataMap() {
	MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
	body.set("name 1", "value 1");
	body.add("name 2", "value 2+1");
	body.add("name 2", "value 2+2");
	body.add("name 3", null);

	BodyInserter<MultiValueMap<String, String>, ClientHttpRequest>
			inserter = BodyInserters.fromFormData(body);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("http://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

	StepVerifier.create(request.getBody())
			.consumeNextWith(dataBuffer -> {
				byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(resultBytes);
				DataBufferUtils.release(dataBuffer);
				assertArrayEquals("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8),
						resultBytes);
			})
			.expectComplete()
			.verify();

}
 
Example #26
Source File: BodyInserters.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> insert(ClientHttpRequest outputMessage, Context context) {
	HttpMessageWriter<MultiValueMap<String, HttpEntity<?>>> messageWriter =
			findWriter(context, MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA);
	MultiValueMap<String, HttpEntity<?>> body = this.builder.build();
	return messageWriter.write(Mono.just(body), MULTIPART_DATA_TYPE,
			MediaType.MULTIPART_FORM_DATA, outputMessage, context.hints());
}
 
Example #27
Source File: HttpHandlerConnector.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<ClientHttpResponse> connect(HttpMethod httpMethod, URI uri,
		Function<? super ClientHttpRequest, Mono<Void>> requestCallback) {

	MonoProcessor<ClientHttpResponse> result = MonoProcessor.create();

	MockClientHttpRequest mockClientRequest = new MockClientHttpRequest(httpMethod, uri);
	MockServerHttpResponse mockServerResponse = new MockServerHttpResponse();

	mockClientRequest.setWriteHandler(requestBody -> {
		log("Invoking HttpHandler for ", httpMethod, uri);
		ServerHttpRequest mockServerRequest = adaptRequest(mockClientRequest, requestBody);
		ServerHttpResponse responseToUse = prepareResponse(mockServerResponse, mockServerRequest);
		this.handler.handle(mockServerRequest, responseToUse).subscribe(aVoid -> {}, result::onError);
		return Mono.empty();
	});

	mockServerResponse.setWriteHandler(responseBody ->
			Mono.fromRunnable(() -> {
				log("Creating client response for ", httpMethod, uri);
				result.onNext(adaptResponse(mockServerResponse, responseBody));
			}));

	log("Writing client request for ", httpMethod, uri);
	requestCallback.apply(mockClientRequest).subscribe(aVoid -> {}, result::onError);

	return result;
}
 
Example #28
Source File: WiretapConnectorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void captureAndClaim() {
	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, "/test");
	ClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
			.header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build();

	WiretapConnector wiretapConnector = new WiretapConnector(connector);
	ExchangeFunction function = ExchangeFunctions.create(wiretapConnector);
	function.exchange(clientRequest).block(ofMillis(0));

	WiretapConnector.Info actual = wiretapConnector.claimRequest("1");
	ExchangeResult result = actual.createExchangeResult(Duration.ZERO, null);
	assertEquals(HttpMethod.GET, result.getMethod());
	assertEquals("/test", result.getUrl().toString());
}
 
Example #29
Source File: BodyInserterRequestBuilderWriteToInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public BodyInserterRequestBuilderWriteToInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
    super(traceContext, methodDescriptor);

    final SpringWebFluxPluginConfig config = new SpringWebFluxPluginConfig(traceContext.getProfilerConfig());
    final ClientRequestAdaptor<ClientRequestWrapper> clientRequestAdaptor = ClientRequestWrapperAdaptor.INSTANCE;
    this.clientRequestRecorder = new ClientRequestRecorder<ClientRequestWrapper>(config.isParam(), clientRequestAdaptor);

    final CookieExtractor<ClientHttpRequest> cookieExtractor = new ClientHttpRequestCookieExtractor();
    this.cookieRecorder = CookieRecorderFactory.newCookieRecorder(config.getHttpDumpConfig(), cookieExtractor);

    final ClientHttpRequestClientHeaderAdaptor clientHeaderAdaptor = new ClientHttpRequestClientHeaderAdaptor();
    this.requestTraceWriter = new DefaultRequestTraceWriter<ClientHttpRequest>(clientHeaderAdaptor, traceContext);
}
 
Example #30
Source File: ClientHttpRequestClientHeaderAdaptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void setHeader(final ClientHttpRequest request, final String name, final String value) {
    if (request != null && request.getHeaders() != null) {
        final HttpHeaders httpHeaders = request.getHeaders();
        httpHeaders.put(name, Arrays.asList(value));
        if (isDebug) {
            logger.debug("Set header {}={}", name, value);
        }
    }
}