Java Code Examples for org.springframework.web.reactive.function.server.ServerResponse

Following code examples demonstrate how to use org.springframework.web.reactive.function.server.ServerResponsefrom spring-framework. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.springframework.web.reactive.function.server.ServerResponseand various code implementation of this class.

	public Mono<ServerResponse> get(ServerRequest request) {
		Person q = new Person();
	    final Mono<Person> person = Mono.just(q);
	    return person
	        .flatMap(p -> ok().contentType(APPLICATION_JSON).body(fromPublisher(person, Person.class)))
	        .switchIfEmpty(notFound().build());
	} 


	public Mono<ServerResponse> post(ServerRequest request) {
	    final Mono<Person> person = request.bodyToMono(Person.class);
	    final UUID id = UUID.randomUUID();
	    return created(UriComponentsBuilder.fromPath("people/" + id).build().toUri())
	        .contentType(APPLICATION_JSON)
	        .body(
	            fromPublisher(
	                person.map(p -> new Person(p, id)).flatMap(this::save), Person.class));
	  } 

  public Mono<ServerResponse> save(ServerRequest request) {
    Mono<Task> task = request.bodyToMono(Task.class);
    return request.bodyToMono(Task.class)
        .transform(service::save)
        .flatMap(it -> ok().body(fromObject(it)))
        .switchIfEmpty(badRequest().build());
  } 

  public Mono<ServerResponse> hello(ServerRequest request) {
    return ok()
        .contentType(TEXT_PLAIN)
        .body(fromObject("Hello, Spring"));
  } 

    public Mono<ServerResponse> addMsg(ServerRequest serverRequest) {
        String id = serverRequest.pathVariable("id");
        String name = serverRequest.pathVariable("name");
        users = Flux.just(new User(id, name));
        return ok().build();
    } 

    public Mono<ServerResponse> sendMessage(ServerRequest serverRequest) {
        return status(status).contentType(MediaType.TEXT_EVENT_STREAM)
                .body(users, new ParameterizedTypeReference<User>() {
                }).doAfterSuccessOrError((serverResponse, throwable) -> {
                    users = Flux.empty();
                });
    } 

    public RouterFunction<ServerResponse> echoRouter() {
        return route()
            .GET("/echo", request -> ok().body(request.bodyToMono(String.class), String.class))
            .GET("/noop", request -> noContent().build())
            .build();
    } 

    Mono<ServerResponse> postMessage(ServerRequest req) {
        return req.bodyToMono(Message.class)
                .flatMap(b -> Message.validator.validateToEither(b)
                        .bimap(ConstraintViolations::details, this.messages::add)
                        .fold(v -> badRequest().syncBody(v), body -> ok().syncBody(b)));
    } 

    public RouterFunction<ServerResponse> routes() {
        return route()
                .GET("/messages", this::getMessages)
                .POST("/messages", this::postMessage)
                .build();
    } 

    public Mono<ServerResponse> getMutant(ServerRequest request) {
        return request.bodyToMono(Mutant.class)
            .flatMap(service::findOrCreateMutant)
            .map(Mutant::isMutant)
            .flatMap(isMutant -> {
                return isMutant ? ok().build() : status(FORBIDDEN).build();
            });
    } 

    public Mono<ServerResponse> delete(ServerRequest serverRequest) {
        long employeeId = Long.valueOf(serverRequest.pathVariable("id"));
        employeeService.deleteById(employeeId);
        return noContent().build();
    } 

    public Mono<ServerResponse> update(ServerRequest serverRequest) {
        long employeeId = Long.valueOf(serverRequest.pathVariable("id"));
        Mono<Employee> employeeMono = serverRequest.bodyToMono(Employee.class);
        try {
            employeeService.updateEmployee(employeeId, employeeMono);
        } catch (EmployeeNotFoundException e) {
            return notFound().build();
        }

        return noContent().build();
    } 

    public Mono<ServerResponse> create(ServerRequest serverRequest) {
        Mono<Employee> employeeMono = serverRequest.bodyToMono(Employee.class);
        Employee savedEmployee = employeeService.save(employeeMono);
        URI uri = UriComponentsBuilder.fromUri(serverRequest.uri()).pathSegment(String.valueOf(savedEmployee.getId())).build().toUri();
        return created(uri).build();
    } 

    public Mono<ServerResponse> findById(ServerRequest serverRequest) {
        String id = serverRequest.pathVariable("id");
        Optional<Employee> optionalEmployee = employeeService.findById(Long.valueOf(id));
        return optionalEmployee.map(employee -> ok().contentType(APPLICATION_JSON).body(fromObject(employee)))
                .orElseGet(() -> notFound().build());
    } 

    public Mono<ServerResponse> isMutant(ServerRequest request) {
        return request.bodyToMono(Mutant.class)
            .flatMap(service::findOrCreate)
            .map(Mutant::isMutant)
            .flatMap(isMutant -> {
                if (isMutant) {
                    return ok().build();
                } else {
                    return status(FORBIDDEN).build();
                }
            });
    } 

  public Mono<ServerResponse> handle(ServerRequest serverRequest) {
    try {
      return permanentRedirect(new URI("index.html")).build();
    } catch (URISyntaxException e) {
      log.error("An error occurred while creating URI.", e);
      return status(HttpStatus.INTERNAL_SERVER_ERROR)
          .syncBody("Error while creating swagger page.");
    }
  } 

    public Mono<ServerResponse> create(ServerRequest serverRequest) {
        Company company = serverRequest.bodyToMono(Company.class).toProcessor().block();
        company = companyService.save(company);
        URI uri = UriComponentsBuilder.fromUri(serverRequest.uri()).pathSegment(String.valueOf(company.getId())).build().toUri();
        return created(uri).build();
    } 

    public Mono<ServerResponse> findById(ServerRequest serverRequest) {
        String id = serverRequest.pathVariable("id");
        Optional<Company> optionalCompany = companyService.findById(Long.valueOf(id));
        return optionalCompany.map(company -> ok().contentType(APPLICATION_JSON).body(fromObject(company)))
                .orElseGet(() -> notFound().build());
    } 

    public Mono<ServerResponse> delete(ServerRequest serverRequest) {
        long companyId = Long.valueOf(serverRequest.pathVariable("id"));
        companyService.delete(companyId);
        return noContent().build();
    } 

    public Mono<ServerResponse> removeEmployee(ServerRequest serverRequest) {
        long companyId = Long.valueOf(serverRequest.pathVariable("companyId"));
        long employeeId = Long.valueOf(serverRequest.pathVariable("employeeId"));
        companyService.removeEmployee(companyId, employeeId);
        return noContent().build();
    } 

    public Mono<ServerResponse> addEmployee(ServerRequest serverRequest) {
        long companyId = Long.valueOf(serverRequest.pathVariable("companyId"));
        Mono<Long> employeeIdMono = serverRequest.bodyToMono(Long.class);
        try {
            companyService.addEmployee(companyId, employeeIdMono);
        } catch (EmployeeNotFoundException | CompanyNotFoundException e) {
            return notFound().build();
        } catch (EmployeeAlreadyEmployedInCompanyException e) {
            return badRequest().body(fromObject(e.getMessage()));
        }

        return noContent().build();
    } 

  public Mono<ServerResponse> save(Mono<TagSaveRequest> tagSaveRequestMono) {
    return tagSaveRequestMono.single()
        .flatMap(tag -> {
          tagStorageRepository.save(Tag.from(tag));
          return noContent().build();
        })
        .onErrorResume(throwable -> badRequest().build());
  } 

  public Mono<ServerResponse> fetchTags(ServerRequest request) {
    Flux<TagResponse> tags = Flux.fromIterable(
        tagStorageRepository.findAll()
            .stream()
            .map(tag -> TagResponse.from(tag, Collections.emptySet()))
            .collect(Collectors.toSet())
    );
    return ok().contentType(MediaType.APPLICATION_JSON).body(tags, TagResponse.class);
  } 

  public Mono<ServerResponse> fetchTag(ServerRequest request) {
    Optional<String> noOptional = Optional.of(request.pathVariable("no"));
    Long no = noOptional.map(Long::valueOf)
        .orElseThrow(() -> new IllegalArgumentException("pathvariable('no') must not be null"));

    Mono<TagResponse> tag = Mono.just(tagStorageRepository.findById(no)
        .orElseThrow(() -> new IllegalArgumentException("tag must not be null")))
        .map(TagResponse::from);

    return tag.single()
        .flatMap(tagResponse ->
            ok().contentType(MediaType.APPLICATION_JSON)
                .body(tag, TagResponse.class))
        .onErrorResume(throwable -> {
          log.error("tag not found", throwable);
          return badRequest().build();
        });
  } 

    public Mono<ServerResponse> deleteUserById(ServerRequest request){
        String id = request.pathVariable("id");
        return this.repository.findById(id)
                .flatMap(user -> this.repository.delete(user)
                .then(ok().build()))
                .switchIfEmpty(notFound().build());
    } 

    public Mono<ServerResponse> getAllUser(ServerRequest request){
        return ok().contentType(APPLICATION_JSON_UTF8)
                .body(this.repository.findAll(),User.class);
    } 

    public Mono<ServerResponse> createUser(ServerRequest request){
        Mono<User> userMono = request.bodyToMono(User.class);
        
        return userMono.flatMap(user->{
            CheckUtil.checkName(user.getName());
            return ok().contentType(APPLICATION_JSON_UTF8)
                    .body(this.repository.save(user),User.class);
        });
    } 

  public Mono<ServerResponse> getProduct(ServerRequest serverRequest) {
    Mono<Product> product = productService.getProduct(serverRequest.pathVariable("id"));
    return product
            .flatMap(p -> ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(fromObject(p)))
            .switchIfEmpty(notFound().build());
  } 

  public Mono<ServerResponse> saveProduct(ServerRequest serverRequest) {
    Mono<Product> product = serverRequest.bodyToMono(Product.class);
    return product
        .flatMap(p -> status(CREATED)
            .contentType(MediaType.APPLICATION_JSON)
            .body(productService.save(p), Product.class));
  } 

  public Mono<ServerResponse> updateProduct(ServerRequest serverRequest) {
    Mono<Product> existingProduct = productService.getProduct(serverRequest.pathVariable("id"));

    return existingProduct
        .flatMap(p -> ok()
            .contentType(MediaType.APPLICATION_JSON)
            .body(productService.save(p), Product.class))
            .switchIfEmpty(notFound().build());
  } 

  public Mono<ServerResponse> getAllProducts(ServerRequest serverRequest) {
    return ServerResponse.ok()
        .body(productService.getAllProducts(), Product.class);
  } 

        Mono<ServerResponse> postToRabbit(ServerRequest request) {
            log.info("Received request {}", request);

            rabbitClient.sendMessage("{}", "test");

            return noContent().build();
        } 

    @Bean
    RouterFunction<ServerResponse> v1Api(
      AmqpTemplate amqpTemplate) {
        var handler = new ApiV1Handler(new RabbitClient(amqpTemplate));

        return
          route(GET("/api/v1/sample"), handler::getSample)
            .and(route(POST("/api/v1/sample"), handler::postToRabbit));
    } 

        Mono<ServerResponse> getSample(ServerRequest request) {
            log.info("Received request {}", request);

            return ok().body(Mono.just("{\"foo\":\"bar\"}"), String.class);
        } 

	public Mono<ServerResponse> all(ServerRequest request) {
		return ok().contentType(APPLICATION_JSON)
				.body(fromPublisher(personRepository.findAll().map(p -> new Person(p)), Person.class));
	} 

	public Mono<ServerResponse> add(ServerRequest request) {
		Mono<Person> person = request.bodyToMono(Person.class);
		UUID id = UUID.randomUUID();
		
		return created(UriComponentsBuilder.fromPath("person/" + id).build().toUri())
				.contentType(APPLICATION_JSON)
				.body(fromPublisher(person.map(p -> new Person(p, id)).flatMap(personRepository::save), Person.class));
	} 

	public Mono<ServerResponse> get(ServerRequest request){
		UUID id = UUID.fromString(request.pathVariable("id"));
		Mono<Person> person = personRepository.findById(id);
		
		return person.flatMap(p -> ok().contentType(APPLICATION_JSON).body(fromPublisher(person, Person.class)))
				.switchIfEmpty(notFound().build());
	} 

Advertisement
Javadoc
Represents a typed server-side HTTP response, as returned by a {@linkplain HandlerFunction handler f

unction or {@linkplain HandlerFilterFunction filter function. @author Arjen Poutsma @author Juergen Hoeller @author Sebastien Deleuze @since 5.0

Read More
Advertisement