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

The following examples show how to use org.springframework.http.client.reactive.ClientHttpRequest. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: BodyInsertersTests.java    License: 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 2
Source Project: spring-analysis-note   Source File: WiretapConnector.java    License: 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 3
Source Project: spring-analysis-note   Source File: ExchangeResult.java    License: 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 4
Source Project: spring-analysis-note   Source File: WiretapConnectorTests.java    License: 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 5
Source Project: java-technology-stack   Source File: BodyInsertersTests.java    License: 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 6
Source Project: java-technology-stack   Source File: WiretapConnector.java    License: 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 7
Source Project: java-technology-stack   Source File: ExchangeResult.java    License: 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 8
Source Project: java-technology-stack   Source File: WiretapConnectorTests.java    License: 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 9
@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 10
Source Project: openapi-generator   Source File: ApiClient.java    License: 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 11
@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 12
@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 13
@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
@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 Project: armeria   Source File: ArmeriaClientHttpConnector.java    License: 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 Project: spring-boot-admin   Source File: InstanceWebProxy.java    License: 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 Project: pinpoint   Source File: ClientHttpRequestCookieExtractor.java    License: 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
@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
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
@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 21
Source Project: spring-analysis-note   Source File: BodyInserters.java    License: 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 22
Source Project: spring-analysis-note   Source File: BodyInserters.java    License: 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 23
Source Project: spring-analysis-note   Source File: DefaultClientRequestBuilder.java    License: MIT License 5 votes vote down vote up
public BodyInserterRequest(HttpMethod method, URI url, HttpHeaders headers,
		MultiValueMap<String, String> cookies, BodyInserter<?, ? super ClientHttpRequest> body,
		Map<String, Object> attributes) {

	this.method = method;
	this.url = url;
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
	this.cookies = CollectionUtils.unmodifiableMultiValueMap(cookies);
	this.body = body;
	this.attributes = Collections.unmodifiableMap(attributes);

	Object id = attributes.computeIfAbsent(LOG_ID_ATTRIBUTE, name -> ObjectUtils.getIdentityHexString(this));
	this.logPrefix = "[" + id + "] ";
}
 
Example 24
Source Project: spring-analysis-note   Source File: DefaultClientRequestBuilder.java    License: 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 Project: spring-analysis-note   Source File: BodyInsertersTests.java    License: 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("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 26
Source Project: spring-analysis-note   Source File: HttpHandlerConnector.java    License: 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 27
Source Project: Moss   Source File: AbstractInstancesProxyController.java    License: 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 28
Source Project: Moss   Source File: AbstractInstancesProxyController.java    License: 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 29
Source Project: java-technology-stack   Source File: BodyInserters.java    License: 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 30
Source Project: java-technology-stack   Source File: BodyInserters.java    License: 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());
}