org.springframework.web.reactive.function.server.HandlerFunction Java Examples

The following examples show how to use org.springframework.web.reactive.function.server.HandlerFunction. 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: RouterFunctionMapping.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void setAttributes(Map<String, Object> attributes, ServerRequest serverRequest,
		HandlerFunction<?> handlerFunction) {

	attributes.put(RouterFunctions.REQUEST_ATTRIBUTE, serverRequest);
	attributes.put(BEST_MATCHING_HANDLER_ATTRIBUTE, handlerFunction);

	PathPattern matchingPattern =
			(PathPattern) attributes.get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE);
	if (matchingPattern != null) {
		attributes.put(BEST_MATCHING_PATTERN_ATTRIBUTE, matchingPattern);
	}
	Map<String, String> uriVariables =
			(Map<String, String>) attributes
					.get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
	if (uriVariables != null) {
		attributes.put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
	}
}
 
Example #2
Source File: WingtipsSpringWebfluxComponentTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<ServerResponse> filter(
    ServerRequest serverRequest,
    HandlerFunction<ServerResponse> handlerFunction
) {
    HttpHeaders httpHeaders = serverRequest.headers().asHttpHeaders();

    if ("true".equals(httpHeaders.getFirst("throw-handler-filter-function-exception"))) {
        ComponentTestController.sleepThread(SLEEP_TIME_MILLIS);
        throw new RuntimeException("Exception thrown from HandlerFilterFunction");
    }

    if ("true".equals(httpHeaders.getFirst("return-exception-in-handler-filter-function-mono"))) {
        return Mono
            .delay(Duration.ofMillis(SLEEP_TIME_MILLIS))
            .map(d -> {
                throw new RuntimeException("Exception returned from HandlerFilterFunction Mono");
            });
    }

    return handlerFunction.handle(serverRequest);
}
 
Example #3
Source File: RouterFunctionMapping.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void setAttributes(Map<String, Object> attributes, ServerRequest serverRequest,
		HandlerFunction<?> handlerFunction) {

	attributes.put(RouterFunctions.REQUEST_ATTRIBUTE, serverRequest);
	attributes.put(BEST_MATCHING_HANDLER_ATTRIBUTE, handlerFunction);

	PathPattern matchingPattern =
			(PathPattern) attributes.get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE);
	if (matchingPattern != null) {
		attributes.put(BEST_MATCHING_PATTERN_ATTRIBUTE, matchingPattern);
	}
	Map<String, String> uriVariables =
			(Map<String, String>) attributes
					.get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
	if (uriVariables != null) {
		attributes.put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
	}
}
 
Example #4
Source File: App.java    From spring-5-examples with MIT License 6 votes vote down vote up
@Bean
RouterFunction routes(final HandlerFunction<ServerResponse> fallbackHandler) {
  return
      nest(
          path("/"),
          nest(
              accept(APPLICATION_JSON),
              route(
                  GET("/api/orders"),
                  getOrdersHandler()
              )
          ).andNest(
              accept(APPLICATION_JSON),
              route(
                  GET("/api"),
                  getCountQueryHandler()
              )
          )
      ).andOther(
          route(
              GET("/**"),
              fallbackHandler
          )
      )
      ;
}
 
Example #5
Source File: App.java    From spring-5-examples with MIT License 6 votes vote down vote up
@Bean
HandlerFunction<ServerResponse> fallbackHandler() {
  return request -> {
    final URL url = Try.of(() -> request.uri().toURL())
                       .getOrElseThrow(() -> new RuntimeException("=/"));
    final String protocol = url.getProtocol();
    final int defaultPort = "https".equals(protocol) ? 443 : 80;
    final int currentPort = url.getPort();
    final int port = currentPort == -1 ? defaultPort : currentPort;
    final String baseUrl = format("%s://%s:%d", protocol, url.getHost(), port);
    return ok().body(Flux.just(
        format("GET orders -> %s/api/orders/", baseUrl),
        format("GET pages -> %s/api/", baseUrl),
        format("GET ** -> %s/", baseUrl)
    ), String.class);
  };
}
 
Example #6
Source File: StudentRouterHandlerCombined.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> returnAllStudentWithCombineFun(){
	
       HandlerFunction<ServerResponse> studentHandler = 
               serverRequest -> 
            	  ServerResponse.ok().body(studentMongoRepository.findAll(), Student.class);
	
	RouterFunction<ServerResponse> studentResponse =
   		RouterFunctions.route(RequestPredicates.GET("/api/f/combine/getAllStudent"),
   				studentHandler);
	
	return studentResponse;
   }
 
Example #7
Source File: ExampleHandlerFilterFunction.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Mono<ServerResponse> filter(ServerRequest serverRequest, HandlerFunction<ServerResponse> handlerFunction) {
    if (serverRequest.pathVariable("name").equalsIgnoreCase("test")) {
        return ServerResponse.status(FORBIDDEN).build();
    }
    return handlerFunction.handle(serverRequest);
}
 
Example #8
Source File: SampleSpringboot2WebFluxSpringConfig.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ServerResponse> filter(
    ServerRequest serverRequest,
    HandlerFunction<ServerResponse> handlerFunction
) {
    HttpHeaders httpHeaders = serverRequest.headers().asHttpHeaders();

    if ("true".equals(httpHeaders.getFirst("throw-handler-filter-function-exception"))) {
        throw ApiException
            .newBuilder()
            .withApiErrors(SampleProjectApiError.ERROR_THROWN_IN_HANDLER_FILTER_FUNCTION)
            .withExceptionMessage("Exception thrown from HandlerFilterFunction")
            .build();
    }

    if ("true".equals(httpHeaders.getFirst("return-exception-in-handler-filter-function-mono"))) {
        return Mono.error(
            ApiException
                .newBuilder()
                .withApiErrors(SampleProjectApiError.ERROR_RETURNED_IN_HANDLER_FILTER_FUNCTION_MONO)
                .withExceptionMessage("Exception returned from HandlerFilterFunction Mono")
                .build()
        );
    }

    return handlerFunction.handle(serverRequest);
}
 
Example #9
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ServerResponse> filter(
    ServerRequest serverRequest,
    HandlerFunction<ServerResponse> handlerFunction
) {
    HttpHeaders httpHeaders = serverRequest.headers().asHttpHeaders();

    if ("true".equals(httpHeaders.getFirst("throw-handler-filter-function-exception"))) {
        throw ApiException
            .newBuilder()
            .withApiErrors(ERROR_THROWN_IN_HANDLER_FILTER_FUNCTION)
            .withExceptionMessage("Exception thrown from HandlerFilterFunction")
            .build();
    }

    if ("true".equals(httpHeaders.getFirst("return-exception-in-handler-filter-function-mono"))) {
        return Mono.error(
            ApiException
                .newBuilder()
                .withApiErrors(ERROR_RETURNED_IN_HANDLER_FILTER_FUNCTION_MONO)
                .withExceptionMessage("Exception returned from HandlerFilterFunction Mono")
                .build()
        );
    }

    return handlerFunction.handle(serverRequest);
}
 
Example #10
Source File: ExplodingHandlerFilterFunction.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ServerResponse> filter(
    ServerRequest serverRequest,
    HandlerFunction<ServerResponse> handlerFunction
) {
    HttpHeaders httpHeaders = serverRequest.headers().asHttpHeaders();

    if ("true".equals(httpHeaders.getFirst("throw-handler-filter-function-exception"))) {
        throw ApiException
            .newBuilder()
            .withApiErrors(SampleProjectApiError.ERROR_THROWN_IN_HANDLER_FILTER_FUNCTION)
            .withExceptionMessage("Exception thrown from HandlerFilterFunction")
            .build();
    }

    if ("true".equals(httpHeaders.getFirst("return-exception-in-handler-filter-function-mono"))) {
        return Mono.error(
            ApiException
                .newBuilder()
                .withApiErrors(SampleProjectApiError.ERROR_RETURNED_IN_HANDLER_FILTER_FUNCTION_MONO)
                .withExceptionMessage("Exception returned from HandlerFilterFunction Mono")
                .build()
        );
    }

    return handlerFunction.handle(serverRequest);
}
 
Example #11
Source File: StudentRouterHandlerCombined.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> returnStudentWithCombineFun(){
	
       HandlerFunction<ServerResponse> studentHandler = 
               serverRequest -> {
            	  int rollNo = getInt(serverRequest.pathVariable("rollNo"));
            	  return ServerResponse.ok().body(studentMongoRepository.findByRollNo(rollNo), Student.class);
            };
	
	RouterFunction<ServerResponse> studentResponse =
   		RouterFunctions.route(RequestPredicates.GET("/api/f/combine/getStudent/{rollNo}"),
   				studentHandler);
	
	return studentResponse;
   }
 
Example #12
Source File: RouterFunctionMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void normal() {
	HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build();
	RouterFunction<ServerResponse> routerFunction = request -> Mono.just(handlerFunction);

	RouterFunctionMapping mapping = new RouterFunctionMapping(routerFunction);
	mapping.setMessageReaders(this.codecConfigurer.getReaders());

	Mono<Object> result = mapping.getHandler(this.exchange);

	StepVerifier.create(result)
			.expectNext(handlerFunction)
			.expectComplete()
			.verify();
}
 
Example #13
Source File: HandlerFunctionAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
	HandlerFunction<?> handlerFunction = (HandlerFunction<?>) handler;
	ServerRequest request = exchange.getRequiredAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
	return handlerFunction.handle(request)
			.map(response -> new HandlerResult(handlerFunction, response, HANDLER_FUNCTION_RETURN_TYPE));
}
 
Example #14
Source File: RouterFunctionMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void normal() {
	HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build();
	RouterFunction<ServerResponse> routerFunction = request -> Mono.just(handlerFunction);

	RouterFunctionMapping mapping = new RouterFunctionMapping(routerFunction);
	mapping.setMessageReaders(this.codecConfigurer.getReaders());

	Mono<Object> result = mapping.getHandler(this.exchange);

	StepVerifier.create(result)
			.expectNext(handlerFunction)
			.expectComplete()
			.verify();
}
 
Example #15
Source File: HandlerFunctionAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
	HandlerFunction<?> handlerFunction = (HandlerFunction<?>) handler;
	ServerRequest request = exchange.getRequiredAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
	return handlerFunction.handle(request)
			.map(response -> new HandlerResult(handlerFunction, response, HANDLER_FUNCTION_RETURN_TYPE));
}
 
Example #16
Source File: MetricbeatImporterConfiguration.java    From sofa-lookout with Apache License 2.0 4 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> metricbeat_importer_bulk_router() {
    RequestPredicate predicate = POST("/beat/_bulk");
    HandlerFunction<ServerResponse> handler = metricbeatMetricImporter()::handle;
    return route(predicate, handler);
}
 
Example #17
Source File: MetricbeatImporterConfiguration.java    From sofa-lookout with Apache License 2.0 4 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> metricbeat_importer_template_router() {
    RequestPredicate predicate = GET("/beat/_template/{template}").or(HEAD("/beat/_template/{template}"));
    HandlerFunction<ServerResponse> handler = metricbeatMetricImporter()::headBeatTemplate;
    return route(predicate, handler);
}
 
Example #18
Source File: HandlerFunctionAdapter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public boolean supports(Object handler) {
	return handler instanceof HandlerFunction;
}
 
Example #19
Source File: ReactiveControllers.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
public HandlerFunction<ServerResponse> routeMonoHandle(){
	HandlerFunction<ServerResponse> handlerMono =
			request -> ok().body(Mono.just("Mono Stream"), String.class);
	    return handlerMono;
}
 
Example #20
Source File: ReactiveControllers.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
public HandlerFunction<ServerResponse> handlerFluxData(){
	HandlerFunction<ServerResponse> handlerFlux =
		    req -> ServerResponse.ok().body(fromObject("Flux Stream from String"));
	    return handlerFlux;
}
 
Example #21
Source File: ReactiveControllers.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
public HandlerFunction<ServerResponse> routeMonoHandle(){
	HandlerFunction<ServerResponse> handlerMono =
			request -> ok().body(Mono.just("Mono Stream"), String.class);
	    return handlerMono;
}
 
Example #22
Source File: ReactiveControllers.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
public HandlerFunction<ServerResponse> handlerFluxData(){
	HandlerFunction<ServerResponse> handlerFlux =
		    req -> ServerResponse.ok().body(fromObject("Flux Stream from String"));
	    return handlerFlux;
}
 
Example #23
Source File: App.java    From spring-5-examples with MIT License 4 votes vote down vote up
@Bean
HandlerFunction<ServerResponse> getCountQueryHandler() {
  return request ->
      ok().contentType(APPLICATION_JSON_UTF8)
          .body(Flux.fromIterable(orderRepository.findAllPrices()), Price.class);
}
 
Example #24
Source File: App.java    From spring-5-examples with MIT License 4 votes vote down vote up
@Bean
HandlerFunction<ServerResponse> getOrdersHandler() {
  return request ->
      ok().contentType(APPLICATION_JSON_UTF8)
          .body(Flux.fromIterable(orderRepository.findAll()), Order.class);
}
 
Example #25
Source File: MetricbeatImporterConfiguration.java    From sofa-lookout with Apache License 2.0 4 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> metricbeat_importer_metadata_router() {
    RequestPredicate predicate = GET("/beat");
    HandlerFunction<ServerResponse> handler = metricbeatMetricImporter()::getMetadata;
    return route(predicate, handler);
}
 
Example #26
Source File: HandlerFunctionAdapter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public boolean supports(Object handler) {
	return handler instanceof HandlerFunction;
}
 
Example #27
Source File: RouterFunctionVisitor.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
@Override
public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) {
	this.routerFunctionData = new RouterFunctionData();
	routerFunctionDatas.add(this.routerFunctionData);
	predicate.accept(this);
}