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

The following examples show how to use org.springframework.web.reactive.function.BodyInserters. 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
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 2
Source Project: tutorials   Source File: SpringWebFluxUnitTest.java    License: 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 3
Source Project: Spring-5.0-By-Example   Source File: FlightService.java    License: 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 4
Source Project: spring-analysis-note   Source File: ResourceHandlerFunction.java    License: 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 Project: POC   Source File: WebFluxIntegrationTests.java    License: 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 6
Source Project: tutorials   Source File: WebClientLoggingIntegrationTest.java    License: 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 7
@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 8
Source Project: Moss   Source File: InstancesProxyController.java    License: 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 9
Source Project: Spring-5.0-By-Example   Source File: TokenService.java    License: 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 10
Source Project: sophia_scaffolding   Source File: ImageCodeHandler.java    License: 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 11
Source Project: spring-cloud-contract   Source File: StubGeneratorTests.java    License: 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 Project: Spring-5.0-By-Example   Source File: TokenService.java    License: 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 13
Source Project: Spring-5.0-Cookbook   Source File: TestReactService.java    License: 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 14
Source Project: java-technology-stack   Source File: ResourceHandlerFunction.java    License: 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 15
Source Project: Spring-5.0-Cookbook   Source File: MicroServiceTest.java    License: 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 16
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 17
Source Project: Spring-5.0-By-Example   Source File: TokenService.java    License: 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 Project: blog-tutorials   Source File: SimpleApiClientTest.java    License: 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 19
@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 20
Source Project: Spring-5.0-By-Example   Source File: TokenService.java    License: 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 21
@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 22
Source Project: microservice-recruit   Source File: ExceptionHandle.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 参考DefaultErrorWebExceptionHandler
 *
 * @param request
 * @return
 */
protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
    Map<String, Object> result = exceptionHandlerResult.get();
    return ServerResponse.status((HttpStatus) result.get("httpStatus"))
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .body(BodyInserters.fromObject(result.get("body")));
}
 
Example 23
@Test
public void modifyRequestBodySSLTimeout() {
	testClient.post().uri("/post")
			.header("Host", "www.modifyrequestbodyssltimeout.org")
			.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
			.body(BodyInserters.fromValue("request")).exchange().expectStatus()
			.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
			.jsonPath("message").isEqualTo("handshake timed out after 1ms");
}
 
Example 24
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
    Throwable error = super.getError(request);
    Map<String, Object> errorPropertiesMap = super.getErrorAttributes(request, false);

    if (error instanceof LightSecurityException) {
        return ServerResponse.status(HttpStatus.UNAUTHORIZED)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(errorPropertiesMap));
    }
    return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .body(BodyInserters.fromObject(errorPropertiesMap));
}
 
Example 25
@Test
public void addApplication() {
    when(capacityManagementService.getApplicationSLA(any())).thenReturn(null);
    when(capacityManagementService.addApplicationSLA(any())).thenReturn(Observable.empty());

    testClient.post().body(BodyInserters.fromObject(SAMPLE_SLA_REPRESENTATION)).exchange()
            .expectStatus().is2xxSuccessful()
            .expectHeader().valueEquals(HttpHeaders.LOCATION, baseURI + SAMPLE_SLA.getAppName())
            .expectBody().isEmpty();

    verify(capacityManagementService, times(1)).getApplicationSLA(any());
    verify(capacityManagementService, times(1)).addApplicationSLA(any());
}
 
Example 26
Source Project: spring-analysis-note   Source File: DefaultClientRequestBuilder.java    License: 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 27
Source Project: spring-analysis-note   Source File: DefaultWebClient.java    License: 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 28
@Test
public void savingPostsWhenNoCredentialsThenUnauthorized() throws Exception {
    this.rest
        .post()
        .uri("/posts")
        .body(BodyInserters.fromObject(Post.builder().title("title test").content("content test").build()))
        .exchange()
        .expectStatus().isUnauthorized()
        .expectBody().isEmpty();
}
 
Example 29
Source Project: tutorials   Source File: GlobalErrorWebExceptionHandler.java    License: MIT License 5 votes vote down vote up
private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {

        final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false);

        return ServerResponse.status(HttpStatus.BAD_REQUEST)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .body(BodyInserters.fromObject(errorPropertiesMap));
    }
 
Example 30
@Override
public Mono<ServerResponse> syncBody(Object body) {
	Assert.notNull(body, "Body must not be null");
	Assert.isTrue(!(body instanceof Publisher),
			"Please specify the element class by using body(Publisher, Class)");

	return new DefaultEntityResponseBuilder<>(body,
			BodyInserters.fromObject(body))
			.status(this.statusCode)
			.headers(this.headers)
			.cookies(cookies -> cookies.addAll(this.cookies))
			.hints(hints -> hints.putAll(this.hints))
			.build()
			.map(entityResponse -> entityResponse);
}