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

The following examples show how to use org.springframework.web.reactive.result.view.ViewResolver. 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
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 2
@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 3
@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 4
@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 5
@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
@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 7
@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 8
@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 9
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 10
Source Project: microservice-recruit   Source File: GatewayApplication.java    License: 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 11
Source Project: influx-proxy   Source File: WebExceptionConfig.java    License: Apache License 2.0 5 votes vote down vote up
public WebExceptionConfig(ServerProperties serverProperties,
                                     ResourceProperties resourceProperties,
                                     ObjectProvider<ViewResolver> viewResolversProvider,
                                     ServerCodecConfigurer serverCodecConfigurer,
                                     ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.orderedStream()
            .collect(Collectors.toList());
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example 12
public GlobalErrorWebFluxConfiguration(
        ApplicationContext applicationContext,
        ResourceProperties resourceProperties,
        List<ViewResolver> viewResolvers,
        ServerCodecConfigurer serverCodecConfigurer
) {
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolvers;
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example 13
Source Project: spring-analysis-note   Source File: ServerResponseResultHandler.java    License: 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 14
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 15
Source Project: spring-analysis-note   Source File: WebFluxConfigurationSupport.java    License: MIT License 5 votes vote down vote up
@Bean
public ServerResponseResultHandler serverResponseResultHandler(
		ServerCodecConfigurer serverCodecConfigurer) {
	List<ViewResolver> resolvers = getViewResolverRegistry().getViewResolvers();
	ServerResponseResultHandler handler = new ServerResponseResultHandler();
	handler.setMessageWriters(serverCodecConfigurer.getWriters());
	handler.setViewResolvers(resolvers);
	return handler;
}
 
Example 16
@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 17
@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 18
Source Project: spring-analysis-note   Source File: ViewResolverRegistryTests.java    License: 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 19
Source Project: open-capacity-platform   Source File: ErrorHandlerConfig.java    License: 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 20
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 21
Source Project: spring-microservice-exam   Source File: GatewayExceptionConfig.java    License: 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 22
Source Project: SpringBlade   Source File: ErrorHandlerConfiguration.java    License: 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 23
Source Project: open-cloud   Source File: ApiConfiguration.java    License: 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 24
Source Project: JetfireCloud   Source File: ExceptionAutoConfiguration.java    License: 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 25
Source Project: fw-spring-cloud   Source File: FwGatewayErrorConfigure.java    License: 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 26
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
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 Project: sophia_scaffolding   Source File: ErrorHandler.java    License: 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 Project: sophia_scaffolding   Source File: ErrorHandler.java    License: 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
@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;
		}
	});
}