Java Code Examples for org.springframework.web.reactive.function.BodyInserter

The following examples show how to use org.springframework.web.reactive.function.BodyInserter. 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
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return this.inserter.insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example 2
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return inserter().insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example 3
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return this.inserter.insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example 4
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return inserter().insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example 5
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 6
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 7
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 8
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 9
public BodyInserterResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies,
		BodyInserter<T, ? super ServerHttpResponse> body, Map<String, Object> hints) {

	super(statusCode, headers, cookies, hints);
	Assert.notNull(body, "BodyInserter must not be null");
	this.inserter = body;
}
 
Example 10
public DefaultEntityResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies, T entity,
		BodyInserter<T, ? super ServerHttpResponse> inserter, Map<String, Object> hints) {

	super(statusCode, headers, cookies, hints);
	this.entity = entity;
	this.inserter = inserter;
}
 
Example 11
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 12
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 13
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 14
@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 15
public BodyInserterResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies,
		BodyInserter<T, ? super ServerHttpResponse> body, Map<String, Object> hints) {

	super(statusCode, headers, cookies);
	Assert.notNull(body, "BodyInserter must not be null");
	this.inserter = body;
	this.hints = hints;
}
 
Example 16
public DefaultEntityResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies, T entity,
		BodyInserter<T, ? super ServerHttpResponse> inserter, Map<String, Object> hints) {

	super(statusCode, headers, cookies);
	this.entity = entity;
	this.inserter = inserter;
	this.hints = hints;
}
 
Example 17
Source Project: soul   Source File: FileSizeFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) {
    MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
    if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)) {
        ServerRequest serverRequest = ServerRequest.create(exchange,
                messageReaders);
        return serverRequest.bodyToMono(DataBuffer.class)
                .flatMap(size -> {
                    if (size.capacity() > BYTES_PER_MB * maxSize) {
                        ServerHttpResponse response = exchange.getResponse();
                        response.setStatusCode(HttpStatus.BAD_REQUEST);
                        Object error = SoulResultWarp.error(SoulResultEnum.PAYLOAD_TOO_LARGE.getCode(), SoulResultEnum.PAYLOAD_TOO_LARGE.getMsg(), null);
                        return WebFluxResultUtils.result(exchange, error);
                    }
                    BodyInserter bodyInserter = BodyInserters.fromPublisher(Mono.just(size), DataBuffer.class);
                    HttpHeaders headers = new HttpHeaders();
                    headers.putAll(exchange.getRequest().getHeaders());
                    headers.remove(HttpHeaders.CONTENT_LENGTH);
                    CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
                            exchange, headers);
                    return bodyInserter.insert(outputMessage, new BodyInserterContext())
                            .then(Mono.defer(() -> {
                                ServerHttpRequest decorator = decorate(exchange, outputMessage);
                                return chain.filter(exchange.mutate().request(decorator).build());

                            }));
                });
    }
    return chain.filter(exchange);

}
 
Example 18
public Flux<Void> send(Mail mail){
  final BodyInserter<SendgridMail, ReactiveHttpOutputMessage> body = BodyInserters
      .fromObject(SendgridMail.builder().content(mail.getMessage()).from(mail.getFrom()).to(mail.getTo()).subject(mail.getSubject()).build());
  return this.webClient.mutate().baseUrl(this.url).build().post()
      .uri("/v3/mail/send")
      .body(body)
      .header("Authorization","Bearer " + this.apiKey)
      .header("Content-Type","application/json")
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Error on send email"))
      ).bodyToFlux(Void.class);
}
 
Example 19
Source Project: Spring-5.0-By-Example   Source File: MailSender.java    License: MIT License 5 votes vote down vote up
public Flux<Void> send(Mail mail){
  final BodyInserter<SendgridMail, ReactiveHttpOutputMessage> body = BodyInserters
      .fromObject(SendgridMail.builder().content(mail.getMessage()).from(mail.getFrom()).to(mail.getTo()).subject(mail.getSubject()).build());
  return this.webClient.mutate().baseUrl(this.url).build().post()
      .uri("/v3/mail/send")
      .body(body)
      .header("Authorization","Bearer " + this.apiKey)
      .header("Content-Type","application/json")
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Error on send email"))
      ).bodyToFlux(Void.class);
}
 
Example 20
Source Project: tutorials   Source File: WebClientController.java    License: MIT License 5 votes vote down vote up
public void demonstrateWebClient() {
    // request
    WebClient.UriSpec<WebClient.RequestBodySpec> request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST);
    WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post();

    // request body specifications
    WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST)
        .uri("/resource");
    WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post()
        .uri(URI.create("/resource"));

    // request header specification
    WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));
    WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data"));

    // inserters
    BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters
            .fromPublisher(Subscriber::onComplete, String.class);

    LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("key1", "value1");
    map.add("key2", "value2");

    // BodyInserter<MultiValueMap<String, ?>, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map);
    BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body");

    // responses
    WebClient.ResponseSpec response1 = uri1.body(inserter3)
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .acceptCharset(Charset.forName("UTF-8"))
        .ifNoneMatch("*")
        .ifModifiedSince(ZonedDateTime.now())
        .retrieve();
    WebClient.ResponseSpec response2 = requestSpec2.retrieve();

}
 
Example 21
Source Project: spring-analysis-note   Source File: DefaultClientRequestBuilder.java    License: MIT License 4 votes vote down vote up
@Override
public ClientRequest.Builder body(BodyInserter<?, ? super ClientHttpRequest> inserter) {
	this.body = inserter;
	return this;
}
 
Example 22
Source Project: spring-analysis-note   Source File: DefaultClientRequestBuilder.java    License: MIT License 4 votes vote down vote up
@Override
public BodyInserter<?, ? super ClientHttpRequest> body() {
	return this.body;
}
 
Example 23
Source Project: spring-analysis-note   Source File: DefaultWebClient.java    License: MIT License 4 votes vote down vote up
@Override
public RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter) {
	this.inserter = inserter;
	return this;
}
 
Example 24
@Override
public Mono<ServerResponse> body(BodyInserter<?, ? super ServerHttpResponse> inserter) {
	return Mono.just(
			new BodyInserterResponse<>(this.statusCode, this.headers, this.cookies, inserter, this.hints));
}
 
Example 25
public DefaultEntityResponseBuilder(T entity, BodyInserter<T, ? super ServerHttpResponse> inserter) {
	this.entity = entity;
	this.inserter = inserter;
}
 
Example 26
@Override
public BodyInserter<T, ? super ServerHttpResponse> inserter() {
	return this.inserter;
}
 
Example 27
Source Project: spring-analysis-note   Source File: DefaultWebTestClient.java    License: MIT License 4 votes vote down vote up
@Override
public RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter) {
	this.bodySpec.body(inserter);
	return this;
}
 
Example 28
Source Project: open-cloud   Source File: GatewayContextFilter.java    License: MIT License 4 votes vote down vote up
/**
 * ReadFormData
 * @param exchange
 * @param chain
 * @return
 */
private Mono<Void> readFormData(ServerWebExchange exchange,WebFilterChain chain,GatewayContext gatewayContext){
    HttpHeaders headers = exchange.getRequest().getHeaders();
    return exchange.getFormData()
            .doOnNext(multiValueMap -> {
                gatewayContext.setFormData(multiValueMap);
                gatewayContext.getAllRequestData().addAll(multiValueMap);
                log.debug("[GatewayContext]Read FormData Success");
            })
            .then(Mono.defer(() -> {
                Charset charset = headers.getContentType().getCharset();
                charset = charset == null? StandardCharsets.UTF_8:charset;
                String charsetName = charset.name();
                MultiValueMap<String, String> formData = gatewayContext.getFormData();
                /*
                 * formData is empty just return
                 */
                if(null == formData || formData.isEmpty()){
                    return chain.filter(exchange);
                }
                StringBuilder formDataBodyBuilder = new StringBuilder();
                String entryKey;
                List<String> entryValue;
                try {
                    /*
                     * repackage form data
                     */
                    for (Map.Entry<String, List<String>> entry : formData.entrySet()) {
                        entryKey = entry.getKey();
                        entryValue = entry.getValue();
                        if (entryValue.size() > 1) {
                            for(String value : entryValue){
                                formDataBodyBuilder.append(entryKey).append("=").append(URLEncoder.encode(value, charsetName)).append("&");
                            }
                        } else {
                            formDataBodyBuilder.append(entryKey).append("=").append(URLEncoder.encode(entryValue.get(0), charsetName)).append("&");
                        }
                    }
                }catch (UnsupportedEncodingException e){}
                /*
                 * substring with the last char '&'
                 */
                String formDataBodyString = "";
                if(formDataBodyBuilder.length()>0){
                    formDataBodyString = formDataBodyBuilder.substring(0, formDataBodyBuilder.length() - 1);
                }
                /*
                 * get data bytes
                 */
                byte[] bodyBytes =  formDataBodyString.getBytes(charset);
                int contentLength = bodyBytes.length;
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.putAll(exchange.getRequest().getHeaders());
                httpHeaders.remove(HttpHeaders.CONTENT_LENGTH);
                /*
                 * in case of content-length not matched
                 */
                httpHeaders.setContentLength(contentLength);
                /*
                 * use BodyInserter to InsertFormData Body
                 */
                BodyInserter<String, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromObject(formDataBodyString);
                CachedBodyOutputMessage cachedBodyOutputMessage = new CachedBodyOutputMessage(exchange, httpHeaders);
                log.debug("[GatewayContext]Rewrite Form Data :{}",formDataBodyString);
                return bodyInserter.insert(cachedBodyOutputMessage,  new BodyInserterContext())
                        .then(Mono.defer(() -> {
                            ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(
                                    exchange.getRequest()) {
                                @Override
                                public HttpHeaders getHeaders() {
                                    return httpHeaders;
                                }
                                @Override
                                public Flux<DataBuffer> getBody() {
                                    return cachedBodyOutputMessage.getBody();
                                }
                            };
                            return chain.filter(exchange.mutate().request(decorator).build());
                        }));
            }));
}
 
Example 29
@Override
public ClientRequest.Builder body(BodyInserter<?, ? super ClientHttpRequest> inserter) {
	this.body = inserter;
	return this;
}
 
Example 30
@Override
public BodyInserter<?, ? super ClientHttpRequest> body() {
	return this.body;
}