org.springframework.web.reactive.function.BodyInserter Java Examples
The following examples show how to use
org.springframework.web.reactive.function.BodyInserter.
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: InstanceWebProxy.java From spring-boot-admin with Apache License 2.0 | 6 votes |
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 #2
Source File: DefaultEntityResponseBuilder.java From spring-analysis-note with MIT License | 6 votes |
@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
Source File: ApiClient.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: DefaultEntityResponseBuilder.java From java-technology-stack with MIT License | 6 votes |
@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 File: DefaultServerResponseBuilder.java From java-technology-stack with MIT License | 6 votes |
@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 #6
Source File: DefaultServerResponseBuilder.java From spring-analysis-note with MIT License | 6 votes |
@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 #7
Source File: DefaultEntityResponseBuilder.java From java-technology-stack with MIT License | 5 votes |
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 #8
Source File: AbstractInstancesProxyController.java From Moss with Apache License 2.0 | 5 votes |
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 #9
Source File: AbstractInstancesProxyController.java From Moss with Apache License 2.0 | 5 votes |
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 #10
Source File: DefaultClientRequestBuilder.java From java-technology-stack with MIT License | 5 votes |
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 #11
Source File: DefaultClientRequestBuilder.java From java-technology-stack with MIT License | 5 votes |
@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 #12
Source File: DefaultServerResponseBuilder.java From java-technology-stack with MIT License | 5 votes |
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 #13
Source File: DefaultClientRequestBuilder.java From spring-analysis-note with MIT License | 5 votes |
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
Source File: FileSizeFilter.java From soul with Apache License 2.0 | 5 votes |
@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 #15
Source File: MailSender.java From Learning-Path-Spring-5-End-to-End-Programming with MIT License | 5 votes |
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 #16
Source File: MailSender.java From Spring-5.0-By-Example with MIT License | 5 votes |
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 #17
Source File: WebClientController.java From tutorials with MIT License | 5 votes |
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 #18
Source File: DefaultServerResponseBuilder.java From spring-analysis-note with MIT License | 5 votes |
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 #19
Source File: DefaultEntityResponseBuilder.java From spring-analysis-note with MIT License | 5 votes |
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 #20
Source File: DefaultClientRequestBuilder.java From spring-analysis-note with MIT License | 5 votes |
@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 #21
Source File: HttpRequest.java From charon-spring-boot-starter with Apache License 2.0 | 4 votes |
@Override public BodyInserter<?, ? super ClientHttpRequest> body() { return delegate.body(); }
Example #22
Source File: DefaultWebTestClient.java From spring-analysis-note with MIT License | 4 votes |
@Override public RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter) { this.bodySpec.body(inserter); return this; }
Example #23
Source File: DefaultEntityResponseBuilder.java From java-technology-stack with MIT License | 4 votes |
@Override public BodyInserter<T, ? super ServerHttpResponse> inserter() { return this.inserter; }
Example #24
Source File: DefaultWebTestClient.java From java-technology-stack with MIT License | 4 votes |
@Override public RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter) { this.bodySpec.body(inserter); return this; }
Example #25
Source File: WebReactiveHttpClient.java From feign-reactive with Apache License 2.0 | 4 votes |
protected BodyInserter<?, ? super ClientHttpRequest> provideBody(ReactiveHttpRequest request) { return bodyActualType != null ? BodyInserters.fromPublisher(request.body(), bodyActualType) : BodyInserters.empty(); }
Example #26
Source File: DefaultWebClient.java From spring-analysis-note with MIT License | 4 votes |
@Override public RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter) { this.inserter = inserter; return this; }
Example #27
Source File: HttpRequestMapper.java From charon-spring-boot-starter with Apache License 2.0 | 4 votes |
BodyInserter<Flux<DataBuffer>, ReactiveHttpOutputMessage> extractBody(ServerHttpRequest request) { return fromDataBuffers(request.getBody()); }
Example #28
Source File: DefaultServerResponseBuilder.java From spring-analysis-note with MIT License | 4 votes |
@Override public Mono<ServerResponse> body(BodyInserter<?, ? super ServerHttpResponse> inserter) { return Mono.just( new BodyInserterResponse<>(this.statusCode, this.headers, this.cookies, inserter, this.hints)); }
Example #29
Source File: HttpRequest.java From charon-spring-boot-starter with Apache License 2.0 | 4 votes |
public void setBody(BodyInserter<?, ? super ClientHttpRequest> body) { delegate = from(delegate) .body(body) .build(); }
Example #30
Source File: ModifyRequestBodyGatewayFilterFactory.java From spring-cloud-gateway with Apache License 2.0 | 4 votes |
@Override @SuppressWarnings("unchecked") public GatewayFilter apply(Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { Class inClass = config.getInClass(); ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders); // TODO: flux or mono Mono<?> modifiedBody = serverRequest.bodyToMono(inClass) .flatMap(originalBody -> config.getRewriteFunction() .apply(exchange, originalBody)) .switchIfEmpty(Mono.defer(() -> (Mono) config.getRewriteFunction() .apply(exchange, null))); BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, config.getOutClass()); HttpHeaders headers = new HttpHeaders(); headers.putAll(exchange.getRequest().getHeaders()); // the new content type will be computed by bodyInserter // and then set in the request decorator headers.remove(HttpHeaders.CONTENT_LENGTH); // if the body is changing content types, set it here, to the bodyInserter // will know about it if (config.getContentType() != null) { headers.set(HttpHeaders.CONTENT_TYPE, config.getContentType()); } CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage( exchange, headers); return bodyInserter.insert(outputMessage, new BodyInserterContext()) // .log("modify_request", Level.INFO) .then(Mono.defer(() -> { ServerHttpRequest decorator = decorate(exchange, headers, outputMessage); return chain .filter(exchange.mutate().request(decorator).build()); })).onErrorResume( (Function<Throwable, Mono<Void>>) throwable -> release( exchange, outputMessage, throwable)); } @Override public String toString() { return filterToStringCreator(ModifyRequestBodyGatewayFilterFactory.this) .append("Content type", config.getContentType()) .append("In class", config.getInClass()) .append("Out class", config.getOutClass()).toString(); } }; }