org.springframework.web.reactive.function.BodyInserters Java Examples

The following examples show how to use org.springframework.web.reactive.function.BodyInserters. 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: InstancesProxyController.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD,
		RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Flux<InstanceWebProxy.InstanceResponse> endpointProxy(
		@PathVariable("applicationName") String applicationName, ServerHttpRequest request) {
	String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + APPLICATION_MAPPED_PATH, request);
	URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true)
			.toUri();

	Flux<DataBuffer> cachedBody = request.getBody().map((b) -> {
		int readableByteCount = b.readableByteCount();
		DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(readableByteCount);
		dataBuffer.write(b.asByteBuffer());
		DataBufferUtils.release(b);
		return dataBuffer;
	}).cache();

	return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), uri, request.getMethod(),
			this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(cachedBody));
}
 
Example #2
Source File: WebFluxIntegrationTests.java    From POC with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Invalid Data")
void testCreateBookFail() {
	Book book = Book.builder().author("Raja").text("This is a Test Book")
			.title(RandomStringUtils.randomAlphanumeric(200)).build();

	this.webTestClient.post().uri("/books").contentType(MediaType.APPLICATION_JSON)
			.accept(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(book)).exchange().expectStatus()
			.isBadRequest().expectHeader().contentType(MediaType.APPLICATION_JSON).expectBody()
			.jsonPath("$.message").isNotEmpty().jsonPath("$.errors.[0].defaultMessage")
			.isEqualTo("size must be between 0 and 140");

	book = Book.builder().build();
	this.webTestClient.post().uri("/books").contentType(MediaType.APPLICATION_JSON)
			.accept(MediaType.APPLICATION_JSON).body(Mono.just(book), Book.class).exchange().expectStatus()
			.isBadRequest().expectHeader().contentType(MediaType.APPLICATION_JSON).expectBody()
			.jsonPath("$.message").isNotEmpty().jsonPath("$.errors.[0].defaultMessage")
			.isEqualTo("must not be blank");
}
 
Example #3
Source File: SpringWebFluxUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenReactiveClient_whenRequested_shouldReturnResponse() throws Exception {
    
    HttpClient httpClient = new HttpClient();
    httpClient.start();

    ClientHttpConnector clientConnector = new JettyClientHttpConnector(httpClient);
    WebClient client = WebClient.builder()
        .clientConnector(clientConnector)
        .build();
    String responseContent = client.post()
        .uri(uri())
        .contentType(MediaType.TEXT_PLAIN)
        .body(BodyInserters.fromPublisher(Mono.just(CONTENT), String.class))
        .retrieve()
        .bodyToMono(String.class)
        .block();
    Assert.assertNotNull(responseContent);
    Assert.assertEquals(CONTENT, responseContent);
}
 
Example #4
Source File: ResourceHandlerFunction.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
	HttpMethod method = request.method();
	if (method != null) {
		switch (method) {
			case GET:
				return EntityResponse.fromObject(this.resource).build()
						.map(response -> response);
			case HEAD:
				Resource headResource = new HeadMethodResource(this.resource);
				return EntityResponse.fromObject(headResource).build()
						.map(response -> response);
			case OPTIONS:
				return ServerResponse.ok()
						.allow(SUPPORTED_METHODS)
						.body(BodyInserters.empty());
		}
	}
	return ServerResponse.status(HttpStatus.METHOD_NOT_ALLOWED)
			.allow(SUPPORTED_METHODS)
			.body(BodyInserters.empty());
}
 
Example #5
Source File: FlightService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "flight-query",groupKey = "airline-flights-query",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Flux<Flight> search(@NonNull FlightSearch query){
  return discoveryService.serviceAddressFor(this.flightsService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address + "/query").build().post().body(
              BodyInserters.fromObject(query))))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.flightsCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMapMany(res -> res.bodyToFlux(Flight.class));
}
 
Example #6
Source File: ImageCodeHandler.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
	//生成验证码
	String text = producer.createText();
	BufferedImage image = producer.createImage(text);

	//保存验证码信息
	String randomStr = serverRequest.queryParam("randomStr").get();
	redisTemplate.opsForValue().set(CommonConstants.DEFAULT_CODE_KEY + randomStr, text, 60, TimeUnit.SECONDS);

	// 转换流信息写出
	FastByteArrayOutputStream os = new FastByteArrayOutputStream();
	try {
		ImageIO.write(image, "jpeg", os);
	} catch (IOException e) {
		log.error("ImageIO write err", e);
		return Mono.error(e);
	}

	return ServerResponse
		.status(HttpStatus.OK)
		.contentType(MediaType.IMAGE_JPEG)
		.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
}
 
Example #7
Source File: WebClientLoggingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenNettyHttpClientWithWiretap_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() {

    reactor.netty.http.client.HttpClient httpClient = HttpClient
      .create()
      .wiretap(true);
    WebClient
      .builder()
      .clientConnector(new ReactorClientHttpConnector(httpClient))
      .build()
      .post()
      .uri(sampleUrl)
      .body(BodyInserters.fromObject(post))
      .exchange()
      .block();

    verify(nettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains("00000300")));
}
 
Example #8
Source File: GatewayControllerEndpointTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostRouteWithNotExistingPredicate() {

	RouteDefinition testRouteDefinition = new RouteDefinition();
	testRouteDefinition.setUri(URI.create("http://example.org"));

	PredicateDefinition predicateDefinition = new PredicateDefinition(
			"NotExistingPredicate=test-config");
	testRouteDefinition.setPredicates(Collections.singletonList(predicateDefinition));

	testClient.post()
			.uri("http://localhost:" + port + "/actuator/gateway/routes/test-route")
			.accept(MediaType.APPLICATION_JSON)
			.body(BodyInserters.fromValue(testRouteDefinition)).exchange()
			.expectStatus().isBadRequest();
}
 
Example #9
Source File: InstancesProxyController.java    From Moss with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = REQUEST_MAPPING_PATH, method = {RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS})
public Mono<Void> endpointProxy(@PathVariable("instanceId") String instanceId,
                                ServerHttpRequest request,
                                ServerHttpResponse response) {
    String endpointLocalPath = getEndpointLocalPath(request.getPath().pathWithinApplication().value());
    URI uri = UriComponentsBuilder.fromPath(endpointLocalPath)
                                  .query(request.getURI().getRawQuery())
                                  .build(true)
                                  .toUri();

    return super.forward(instanceId, uri, request.getMethod(), request.getHeaders(),
        () -> BodyInserters.fromDataBuffers(request.getBody())).flatMap(clientResponse -> {
        response.setStatusCode(clientResponse.statusCode());
        response.getHeaders().addAll(filterHeaders(clientResponse.headers().asHttpHeaders()));
        return response.writeAndFlushWith(clientResponse.body(BodyExtractors.toDataBuffers()).window(1));
    });
}
 
Example #10
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString((credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #11
Source File: StubGeneratorTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMarkClientAsNotFraud() throws Exception {
	FraudCheck fraudCheck = new FraudCheck();
	fraudCheck.setClientId("1234567890");
	fraudCheck.setLoanAmount(BigDecimal.valueOf(123.123));
	client.put().uri("/fraudcheck")
			.contentType(MediaType.valueOf("application/vnd.fraud.v1+json"))
			.body(BodyInserters.fromObject(json.write(fraudCheck).getJson()))
			.exchange().expectBody().jsonPath("$.fraudCheckStatus").isEqualTo("OK")
			.jsonPath("$.rejectionReason").doesNotExist()
			.consumeWith(verify().jsonPath("$.clientId")
					.jsonPath("$[?(@.loanAmount <= 1000)]")
					.contentType(MediaType.valueOf("application/vnd.fraud.v1+json"))
					.stub("markClientAsNotFraud"))
			.consumeWith(
					WebTestClientRestDocumentation.document("markClientAsNotFraud"));
}
 
Example #12
Source File: TestReactService.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Test
public void testSaveEmps(){
	Employee newEmp = new Employee();
	newEmp.setEmpid(87978);
	newEmp.setAge(22);
	newEmp.setBirthday(new Date(72, 1,22));
	newEmp.setDeptid(362);
	newEmp.setEmail("[email protected]");
	newEmp.setFirstname("Keith");
	newEmp.setLastname("Smith");

	/*
	Mono<ClientResponse> resp = WebClient.create().post().uri("http://localhost:8098/saveEmp").accept(MediaType.APPLICATION_JSON)
             .body(BodyInserters.fromObject(newEmp)).exchange();
	*/
   	ResponseSpec resp = webTestClient.post().uri("http://localhost:9002/saveEmp").accept(MediaType.APPLICATION_JSON_UTF8)
			.body(BodyInserters.fromObject(newEmp)).exchange();
    
		
		
	System.out.println(resp);
	System.out.println("sherwin");
	
}
 
Example #13
Source File: ImageCodeHandler.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
	//生成验证码
	String text = producer.createText();
	BufferedImage image = producer.createImage(text);

	//保存验证码信息
	String randomStr = serverRequest.queryParam("randomStr").get();
	redisTemplate.opsForValue().set(DEFAULT_CODE_KEY + randomStr, text, 120, TimeUnit.SECONDS);

	// 转换流信息写出
	FastByteArrayOutputStream os = new FastByteArrayOutputStream();
	try {
		ImageIO.write(image, "jpeg", os);
	} catch (IOException e) {
		log.error("ImageIO write err", e);
		return Mono.error(e);
	}

	return ServerResponse
		.status(HttpStatus.OK)
		.contentType(MediaType.IMAGE_JPEG)
		.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
}
 
Example #14
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(@NonNull Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString((credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #15
Source File: ReactorTitusMasterClient.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<String> addApplicationSLA(ApplicationSlaRepresentation applicationSLA) {
    Mono<String> x = client.post()
            .uri("/api/v2/management/applications")
            .body(BodyInserters.fromObject(applicationSLA))
            .exchange()
            .flatMap(response -> response.toEntity(String.class))
            .flatMap(response -> {
                if (!response.getStatusCode().is2xxSuccessful()) {
                    return Mono.error(new IOException("Errored with HTTP status code " + response.getStatusCode()));
                }
                List<String> locationHeader = response.getHeaders().getOrDefault("Location", Collections.emptyList());
                if (locationHeader.isEmpty()) {
                    return Mono.error(new IOException("Location header not found in response"));
                }
                return Mono.just(locationHeader.get(0));
            });
    return ReactorExt.toObservable(x);
}
 
Example #16
Source File: SimpleApiClientTest.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Test
@Disabled
public void testPostNewTodoCall() {
  this.webTestClient
    .post()
    .uri("https://jsonplaceholder.typicode.com/todos")
    .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON)
    .body(BodyInserters.fromValue("{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": \"1\"}"))
    .exchange()
    .expectStatus().isCreated()
    .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
    .expectBody()
    .jsonPath("$.title").isNotEmpty()
    .jsonPath("$.body").isNotEmpty()
    .jsonPath("$.userId").isNotEmpty()
    .jsonPath("$.userId").isEqualTo("1")
    .jsonPath("$.id").isNotEmpty();
}
 
Example #17
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString(( credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #18
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 #19
Source File: MicroServiceTest.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Test
public void testSaveEmps(){
	Employee newEmp = new Employee();
	newEmp.setEmpid(87978);
	newEmp.setAge(22);
	newEmp.setBirthday(new Date(72, 1,22));
	newEmp.setDeptid(362);
	newEmp.setEmail("[email protected]");
	newEmp.setFirstname("Keith");
	newEmp.setLastname("Smith");
	

	/*
	Mono<ClientResponse> resp = WebClient.create().post().uri("http://localhost:8098/saveEmp").accept(MediaType.APPLICATION_JSON)
             .body(BodyInserters.fromObject(newEmp)).exchange();
	*/
   	ResponseSpec resp = webTestClient.post().uri("http://localhost:9002/saveEmp").accept(MediaType.APPLICATION_JSON_UTF8)
			.body(BodyInserters.fromObject(newEmp)).exchange();
    
		
		
	System.out.println(resp);
	System.out.println("sherwin");
	
}
 
Example #20
Source File: ResourceHandlerFunction.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
	HttpMethod method = request.method();
	if (method != null) {
		switch (method) {
			case GET:
				return EntityResponse.fromObject(this.resource).build()
						.map(response -> response);
			case HEAD:
				Resource headResource = new HeadMethodResource(this.resource);
				return EntityResponse.fromObject(headResource).build()
						.map(response -> response);
			case OPTIONS:
				return ServerResponse.ok()
						.allow(SUPPORTED_METHODS)
						.body(BodyInserters.empty());
		}
	}
	return ServerResponse.status(HttpStatus.METHOD_NOT_ALLOWED)
			.allow(SUPPORTED_METHODS)
			.body(BodyInserters.empty());
}
 
Example #21
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(@NonNull Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString((credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #22
Source File: HttpIT.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormData() {
    startServerWithoutSecurity(UpperFormRouter.class);

    getWebTestClient()
        .post()
        .body(BodyInserters.fromFormData("text", "test"))
        .exchange()
        .expectBody(String.class)
        .isEqualTo("TEST");
}
 
Example #23
Source File: MailSender.java    From Learning-Path-Spring-5-End-to-End-Programming with 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 #24
Source File: GatewaySampleApplication.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> testFunRouterFunction() {
	RouterFunction<ServerResponse> route = RouterFunctions.route(
			RequestPredicates.path("/testfun"),
			request -> ServerResponse.ok().body(BodyInserters.fromValue("hello")));
	return route;
}
 
Example #25
Source File: DefaultClientRequestBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public <S, P extends Publisher<S>> ClientRequest.Builder body(
		P publisher, ParameterizedTypeReference<S> typeReference) {

	this.body = BodyInserters.fromPublisher(publisher, typeReference);
	return this;
}
 
Example #26
Source File: ApplicationSlaManagementResourceTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void updateApplication() {
    String targetName = SAMPLE_SLA.getAppName();
    when(capacityManagementService.getApplicationSLA(targetName)).thenReturn(SAMPLE_SLA);
    when(capacityManagementService.addApplicationSLA(any())).thenReturn(Observable.empty());

    testClient.put().uri(targetName).body(BodyInserters.fromObject(SAMPLE_SLA_REPRESENTATION)).exchange()
            .expectStatus().isNoContent()
            .expectBody().isEmpty();

    verify(capacityManagementService, times(1)).getApplicationSLA(targetName);
}
 
Example #27
Source File: ApplicationSlaManagementResourceTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void addExistingApplicationFails() {
    when(capacityManagementService.getApplicationSLA(any())).thenReturn(SAMPLE_SLA);

    testClient.post().body(BodyInserters.fromObject(SAMPLE_SLA_REPRESENTATION)).exchange()
            .expectStatus().isEqualTo(HttpStatus.CONFLICT);

    verify(capacityManagementService, times(1)).getApplicationSLA(any());
    verify(capacityManagementService, times(0)).addApplicationSLA(any());
}
 
Example #28
Source File: DefaultWebClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public <T, P extends Publisher<T>> RequestHeadersSpec<?> body(
		P publisher, ParameterizedTypeReference<T> typeReference) {

	this.inserter = BodyInserters.fromPublisher(publisher, typeReference);
	return this;
}
 
Example #29
Source File: CustomExceptionHandler.java    From lion with Apache License 2.0 5 votes vote down vote up
/**
 * 参考DefaultErrorWebExceptionHandler
 */
protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
    Map<String, Object> result = exceptionHandlerResult.get();
    return ServerResponse.status((HttpStatus) result.get("httpStatus"))
            .contentType(MediaType.APPLICATION_JSON)
            .body(BodyInserters.fromValue(result.get("body")));
}
 
Example #30
Source File: DefaultServerResponseBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public <T, P extends Publisher<T>> Mono<ServerResponse> body(P publisher, Class<T> elementClass) {
	Assert.notNull(publisher, "Publisher must not be null");
	Assert.notNull(elementClass, "Element Class must not be null");

	return new DefaultEntityResponseBuilder<>(publisher,
			BodyInserters.fromPublisher(publisher, elementClass))
			.headers(this.headers)
			.status(this.statusCode)
			.build()
			.map(entityResponse -> entityResponse);
}