org.springframework.web.reactive.result.view.ViewResolver Java Examples

The following examples show how to use org.springframework.web.reactive.result.view.ViewResolver. 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: DefaultRenderingResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultContentType() {
	Mono<RenderingResponse> result = RenderingResponse.create("view").build();

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));
	TestView view = new TestView();
	ViewResolver viewResolver = mock(ViewResolver.class);
	given(viewResolver.resolveViewName(any(), any())).willReturn(Mono.just(view));

	List<ViewResolver> viewResolvers = new ArrayList<>();
	viewResolvers.add(viewResolver);

	ServerResponse.Context context = mock(ServerResponse.Context.class);
	given(context.viewResolvers()).willReturn(viewResolvers);

	StepVerifier.create(result.flatMap(response -> response.writeTo(exchange, context)))
			.verifyComplete();

	assertEquals(ViewResolverSupport.DEFAULT_CONTENT_TYPE, exchange.getResponse().getHeaders().getContentType());
}
 
Example #2
Source File: DefaultRenderingResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void defaultContentType() {
	Mono<RenderingResponse> result = RenderingResponse.create("view").build();

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));
	TestView view = new TestView();
	ViewResolver viewResolver = mock(ViewResolver.class);
	when(viewResolver.resolveViewName(any(), any())).thenReturn(Mono.just(view));

	List<ViewResolver> viewResolvers = new ArrayList<>();
	viewResolvers.add(viewResolver);

	ServerResponse.Context context = mock(ServerResponse.Context.class);
	when(context.viewResolvers()).thenReturn(viewResolvers);

	StepVerifier.create(result.flatMap(response -> response.writeTo(exchange, context)))
			.verifyComplete();

	assertEquals(ViewResolverSupport.DEFAULT_CONTENT_TYPE, exchange.getResponse().getHeaders().getContentType());
}
 
Example #3
Source File: DefaultRenderingResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void render() {
	Map<String, Object> model = Collections.singletonMap("foo", "bar");
	Mono<RenderingResponse> result = RenderingResponse.create("view").modelAttributes(model).build();

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));
	ViewResolver viewResolver = mock(ViewResolver.class);
	View view = mock(View.class);
	when(viewResolver.resolveViewName("view", Locale.ENGLISH)).thenReturn(Mono.just(view));
	when(view.render(model, null, exchange)).thenReturn(Mono.empty());

	List<ViewResolver> viewResolvers = new ArrayList<>();
	viewResolvers.add(viewResolver);

	HandlerStrategies mockConfig = mock(HandlerStrategies.class);
	when(mockConfig.viewResolvers()).thenReturn(viewResolvers);

	StepVerifier.create(result)
			.expectNextMatches(response -> "view".equals(response.name()) &&
					model.equals(response.model()))
			.expectComplete()
			.verify();
}
 
Example #4
Source File: WebFluxConfigurationSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void viewResolutionResultHandler() throws Exception {
	ApplicationContext context = loadConfig(CustomViewResolverConfig.class);

	String name = "viewResolutionResultHandler";
	ViewResolutionResultHandler handler = context.getBean(name, ViewResolutionResultHandler.class);
	assertNotNull(handler);

	assertEquals(Ordered.LOWEST_PRECEDENCE, handler.getOrder());

	List<ViewResolver> resolvers = handler.getViewResolvers();
	assertEquals(1, resolvers.size());
	assertEquals(FreeMarkerViewResolver.class, resolvers.get(0).getClass());

	List<View> views = handler.getDefaultViews();
	assertEquals(1, views.size());

	MimeType type = MimeTypeUtils.parseMimeType("application/json;charset=UTF-8");
	assertEquals(type, views.get(0).getSupportedMediaTypes().get(0));
}
 
Example #5
Source File: DefaultRenderingResponseBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	MediaType contentType = exchange.getResponse().getHeaders().getContentType();
	Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
	Stream<ViewResolver> viewResolverStream = context.viewResolvers().stream();

	return Flux.fromStream(viewResolverStream)
			.concatMap(viewResolver -> viewResolver.resolveViewName(name(), locale))
			.next()
			.switchIfEmpty(Mono.error(() ->
					new IllegalArgumentException("Could not resolve view with name '" + name() + "'")))
			.flatMap(view -> {
				List<MediaType> mediaTypes = view.getSupportedMediaTypes();
				return view.render(model(),
						contentType == null && !mediaTypes.isEmpty() ? mediaTypes.get(0) : contentType,
						exchange);
			});
}
 
Example #6
Source File: DefaultRenderingResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void render() {
	Map<String, Object> model = Collections.singletonMap("foo", "bar");
	Mono<RenderingResponse> result = RenderingResponse.create("view").modelAttributes(model).build();

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));
	ViewResolver viewResolver = mock(ViewResolver.class);
	View view = mock(View.class);
	given(viewResolver.resolveViewName("view", Locale.ENGLISH)).willReturn(Mono.just(view));
	given(view.render(model, null, exchange)).willReturn(Mono.empty());

	List<ViewResolver> viewResolvers = new ArrayList<>();
	viewResolvers.add(viewResolver);

	HandlerStrategies mockConfig = mock(HandlerStrategies.class);
	given(mockConfig.viewResolvers()).willReturn(viewResolvers);

	StepVerifier.create(result)
			.expectNextMatches(response -> "view".equals(response.name()) &&
					model.equals(response.model()))
			.expectComplete()
			.verify();
}
 
Example #7
Source File: WebFluxConfigurationSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void viewResolutionResultHandler() throws Exception {
	ApplicationContext context = loadConfig(CustomViewResolverConfig.class);

	String name = "viewResolutionResultHandler";
	ViewResolutionResultHandler handler = context.getBean(name, ViewResolutionResultHandler.class);
	assertNotNull(handler);

	assertEquals(Ordered.LOWEST_PRECEDENCE, handler.getOrder());

	List<ViewResolver> resolvers = handler.getViewResolvers();
	assertEquals(1, resolvers.size());
	assertEquals(FreeMarkerViewResolver.class, resolvers.get(0).getClass());

	List<View> views = handler.getDefaultViews();
	assertEquals(1, views.size());

	MimeType type = MimeTypeUtils.parseMimeType("application/json");
	assertEquals(type, views.get(0).getSupportedMediaTypes().get(0));
}
 
Example #8
Source File: DefaultRenderingResponseBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	MediaType contentType = exchange.getResponse().getHeaders().getContentType();
	Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
	Stream<ViewResolver> viewResolverStream = context.viewResolvers().stream();

	return Flux.fromStream(viewResolverStream)
			.concatMap(viewResolver -> viewResolver.resolveViewName(name(), locale))
			.next()
			.switchIfEmpty(Mono.error(() ->
					new IllegalArgumentException("Could not resolve view with name '" + name() + "'")))
			.flatMap(view -> {
				List<MediaType> mediaTypes = view.getSupportedMediaTypes();
				return view.render(model(),
						contentType == null && !mediaTypes.isEmpty() ? mediaTypes.get(0) : contentType,
						exchange);
			});
}
 
Example #9
Source File: ErrorHandlerConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
public ErrorHandlerConfig(ServerProperties serverProperties,
                                 ResourceProperties resourceProperties,
                                 ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                 ServerCodecConfigurer serverCodecConfigurer,
                                 ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #10
Source File: DefaultHandlerStrategiesBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public DefaultHandlerStrategies(
		List<HttpMessageReader<?>> messageReaders,
		List<HttpMessageWriter<?>> messageWriters,
		List<ViewResolver> viewResolvers,
		List<WebFilter> webFilters,
		List<WebExceptionHandler> exceptionHandlers,
		LocaleContextResolver localeContextResolver) {

	this.messageReaders = unmodifiableCopy(messageReaders);
	this.messageWriters = unmodifiableCopy(messageWriters);
	this.viewResolvers = unmodifiableCopy(viewResolvers);
	this.webFilters = unmodifiableCopy(webFilters);
	this.exceptionHandlers = unmodifiableCopy(exceptionHandlers);
	this.localeContextResolver = localeContextResolver;
}
 
Example #11
Source File: ServerResponseResultHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
	ServerResponse response = (ServerResponse) result.getReturnValue();
	Assert.state(response != null, "No ServerResponse");
	return response.writeTo(exchange, new ServerResponse.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return messageWriters;
		}
		@Override
		public List<ViewResolver> viewResolvers() {
			return viewResolvers;
		}
	});
}
 
Example #12
Source File: GatewayApplication.java    From microservice-recruit with Apache License 2.0 5 votes vote down vote up
@Primary
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                                         ServerCodecConfigurer serverCodecConfigurer) {
    ExceptionHandle jsonExceptionHandler = new ExceptionHandle();
    jsonExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
    jsonExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
    jsonExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
    return jsonExceptionHandler;
}
 
Example #13
Source File: CustomErrorWebFluxAutoConfiguration.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
public CustomErrorWebFluxAutoConfiguration(ServerProperties serverProperties,
                                           ResourceProperties resourceProperties,
                                           ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                           ServerCodecConfigurer serverCodecConfigurer,
                                           ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #14
Source File: GlobalErrorWebFluxConfiguration.java    From light-security with Apache License 2.0 5 votes vote down vote up
public GlobalErrorWebFluxConfiguration(
        ApplicationContext applicationContext,
        ResourceProperties resourceProperties,
        List<ViewResolver> viewResolvers,
        ServerCodecConfigurer serverCodecConfigurer
) {
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolvers;
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #15
Source File: ResourceHandlerFunctionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void createContext() {
	HandlerStrategies strategies = HandlerStrategies.withDefaults();
	context = new ServerResponse.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return strategies.messageWriters();
		}
		@Override
		public List<ViewResolver> viewResolvers() {
			return strategies.viewResolvers();
		}
	};
}
 
Example #16
Source File: GatewayExceptionConfig.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 自定义异常处理
 */
@Primary
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
    GatewayExceptionHandler gatewayExceptionHandler = new GatewayExceptionHandler();
    gatewayExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
    gatewayExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
    gatewayExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
    return gatewayExceptionHandler;
}
 
Example #17
Source File: ViewResolverRegistryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-16431
public void scriptTemplate() {
	this.registry.scriptTemplate().prefix("/").suffix(".html");

	List<ViewResolver> viewResolvers = this.registry.getViewResolvers();
	assertEquals(1, viewResolvers.size());
	assertEquals(ScriptTemplateViewResolver.class, viewResolvers.get(0).getClass());
	DirectFieldAccessor accessor =  new DirectFieldAccessor(viewResolvers.get(0));
	assertEquals("/", accessor.getPropertyValue("prefix"));
	assertEquals(".html", accessor.getPropertyValue("suffix"));
}
 
Example #18
Source File: ErrorHandlerConfiguration.java    From SpringBlade with Apache License 2.0 5 votes vote down vote up
public ErrorHandlerConfiguration(ServerProperties serverProperties,
								 ResourceProperties resourceProperties,
								 ObjectProvider<List<ViewResolver>> viewResolversProvider,
								 ServerCodecConfigurer serverCodecConfigurer,
								 ApplicationContext applicationContext) {
	this.serverProperties = serverProperties;
	this.applicationContext = applicationContext;
	this.resourceProperties = resourceProperties;
	this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
	this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #19
Source File: ApiConfiguration.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 自定义异常处理[@@]注册Bean时依赖的Bean,会从容器中直接获取,所以直接注入即可
 *
 * @param viewResolversProvider
 * @param serverCodecConfigurer
 * @return
 */
@Primary
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                                         ServerCodecConfigurer serverCodecConfigurer, AccessLogService accessLogService) {

    JsonExceptionHandler jsonExceptionHandler = new JsonExceptionHandler(accessLogService);
    jsonExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
    jsonExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
    jsonExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
    log.info("ErrorWebExceptionHandler [{}]", jsonExceptionHandler);
    return jsonExceptionHandler;
}
 
Example #20
Source File: ExceptionAutoConfiguration.java    From JetfireCloud with Apache License 2.0 5 votes vote down vote up
public ExceptionAutoConfiguration(ServerProperties serverProperties,
                                  ResourceProperties resourceProperties,
                                  ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                  ServerCodecConfigurer serverCodecConfigurer,
                                  ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider
            .getIfAvailable(() -> Collections.emptyList());
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #21
Source File: DefaultEntityResponseBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void bodyInserter() {
	String body = "foo";
	Publisher<String> publisher = Mono.just(body);

	Mono<EntityResponse<Publisher<String>>> result = EntityResponse.fromPublisher(publisher, String.class).build();

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));

	ServerResponse.Context context = new ServerResponse.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return Collections.singletonList(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
		}

		@Override
		public List<ViewResolver> viewResolvers() {
			return Collections.emptyList();
		}
	};
	StepVerifier.create(result)
			.consumeNextWith(response -> {
				StepVerifier.create(response.entity())
						.expectNext(body)
						.expectComplete()
						.verify();
				response.writeTo(exchange, context);
			})
			.expectComplete()
			.verify();

	assertNotNull(exchange.getResponse().getBody());
}
 
Example #22
Source File: WebFluxConfigurationSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Bean
public ServerResponseResultHandler serverResponseResultHandler() {
	List<ViewResolver> resolvers = getViewResolverRegistry().getViewResolvers();
	ServerResponseResultHandler handler = new ServerResponseResultHandler();
	handler.setMessageWriters(serverCodecConfigurer().getWriters());
	handler.setViewResolvers(resolvers);
	return handler;
}
 
Example #23
Source File: WebFluxConfigurationSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Bean
public ViewResolutionResultHandler viewResolutionResultHandler() {
	ViewResolverRegistry registry = getViewResolverRegistry();
	List<ViewResolver> resolvers = registry.getViewResolvers();
	ViewResolutionResultHandler handler = new ViewResolutionResultHandler(
			resolvers, webFluxContentTypeResolver(), webFluxAdapterRegistry());
	handler.setDefaultViews(registry.getDefaultViews());
	handler.setOrder(registry.getOrder());
	return handler;
}
 
Example #24
Source File: FwGatewayErrorConfigure.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
public FwGatewayErrorConfigure(ServerProperties serverProperties,
                                 ResourceProperties resourceProperties,
                                 ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                 ServerCodecConfigurer serverCodecConfigurer,
                                 ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #25
Source File: SentinelConfig.java    From lion with Apache License 2.0 5 votes vote down vote up
/**
 * 自定义异常处理,替换 SentinelGatewayBlockExceptionHandler
 */
@Primary
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                                         ServerCodecConfigurer serverCodecConfigurer) {
    CustomExceptionHandler customCallbackExceptionHandler = new CustomExceptionHandler();
    customCallbackExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
    customCallbackExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
    customCallbackExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
    return customCallbackExceptionHandler;
}
 
Example #26
Source File: ErrorHandlerConfiguration.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
public ErrorHandlerConfiguration(ServerProperties serverProperties,
                                 ResourceProperties resourceProperties,
                                 ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                 ServerCodecConfigurer serverCodecConfigurer,
                                 ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #27
Source File: ErrorHandlerConfiguration.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
public ErrorHandlerConfiguration(ServerProperties serverProperties,
                                 ResourceProperties resourceProperties,
                                 ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                 ServerCodecConfigurer serverCodecConfigurer,
                                 ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #28
Source File: ErrorHandler.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
public ErrorHandler(ServerProperties serverProperties,
                    ResourceProperties resourceProperties,
                    ObjectProvider<List<ViewResolver>> viewResolversProvider,
                    ServerCodecConfigurer serverCodecConfigurer,
                    ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #29
Source File: ErrorHandler.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
public ErrorHandler(ServerProperties serverProperties,
                    ResourceProperties resourceProperties,
                    ObjectProvider<List<ViewResolver>> viewResolversProvider,
                    ServerCodecConfigurer serverCodecConfigurer,
                    ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #30
Source File: ServerResponseResultHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
	ServerResponse response = (ServerResponse) result.getReturnValue();
	Assert.state(response != null, "No ServerResponse");
	return response.writeTo(exchange, new ServerResponse.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return messageWriters;
		}
		@Override
		public List<ViewResolver> viewResolvers() {
			return viewResolvers;
		}
	});
}