org.springframework.http.codec.ServerCodecConfigurer Java Examples

The following examples show how to use org.springframework.http.codec.ServerCodecConfigurer. 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: DefaultServerWebExchange.java    From spring-analysis-note with MIT License 6 votes vote down vote up
DefaultServerWebExchange(ServerHttpRequest request, ServerHttpResponse response,
		WebSessionManager sessionManager, ServerCodecConfigurer codecConfigurer,
		LocaleContextResolver localeContextResolver, @Nullable ApplicationContext applicationContext) {

	Assert.notNull(request, "'request' is required");
	Assert.notNull(response, "'response' is required");
	Assert.notNull(sessionManager, "'sessionManager' is required");
	Assert.notNull(codecConfigurer, "'codecConfigurer' is required");
	Assert.notNull(localeContextResolver, "'localeContextResolver' is required");

	// Initialize before first call to getLogPrefix()
	this.attributes.put(ServerWebExchange.LOG_ID_ATTRIBUTE, request.getId());

	this.request = request;
	this.response = response;
	this.sessionMono = sessionManager.getSession(this).cache();
	this.localeContextResolver = localeContextResolver;
	this.formDataMono = initFormData(request, codecConfigurer, getLogPrefix());
	this.multipartDataMono = initMultipartData(request, codecConfigurer, getLogPrefix());
	this.applicationContext = applicationContext;
}
 
Example #2
Source File: RequestMappingHandlerAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	Assert.notNull(this.applicationContext, "ApplicationContext is required");

	if (CollectionUtils.isEmpty(this.messageReaders)) {
		ServerCodecConfigurer codecConfigurer = ServerCodecConfigurer.create();
		this.messageReaders = codecConfigurer.getReaders();
	}
	if (this.argumentResolverConfigurer == null) {
		this.argumentResolverConfigurer = new ArgumentResolverConfigurer();
	}
	if (this.reactiveAdapterRegistry == null) {
		this.reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
	}

	this.methodResolver = new ControllerMethodResolver(this.argumentResolverConfigurer,
			this.reactiveAdapterRegistry, this.applicationContext, this.messageReaders);

	this.modelInitializer = new ModelInitializer(this.methodResolver, this.reactiveAdapterRegistry);
}
 
Example #3
Source File: ControllerMethodResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() {
	ArgumentResolverConfigurer resolvers = new ArgumentResolverConfigurer();
	resolvers.addCustomResolver(new CustomArgumentResolver());
	resolvers.addCustomResolver(new CustomSyncArgumentResolver());

	ServerCodecConfigurer codecs = ServerCodecConfigurer.create();
	codecs.customCodecs().decoder(new ByteArrayDecoder());
	codecs.customCodecs().decoder(new ByteBufferDecoder());

	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
	applicationContext.registerBean(TestControllerAdvice.class);
	applicationContext.refresh();

	this.methodResolver = new ControllerMethodResolver(
			resolvers, ReactiveAdapterRegistry.getSharedInstance(), applicationContext, codecs.getReaders());

	Method method = ResolvableMethod.on(TestController.class).mockCall(TestController::handle).method();
	this.handlerMethod = new HandlerMethod(new TestController(), method);
}
 
Example #4
Source File: DefaultServerWebExchange.java    From java-technology-stack with MIT License 6 votes vote down vote up
DefaultServerWebExchange(ServerHttpRequest request, ServerHttpResponse response,
		WebSessionManager sessionManager, ServerCodecConfigurer codecConfigurer,
		LocaleContextResolver localeContextResolver, @Nullable ApplicationContext applicationContext) {

	Assert.notNull(request, "'request' is required");
	Assert.notNull(response, "'response' is required");
	Assert.notNull(sessionManager, "'sessionManager' is required");
	Assert.notNull(codecConfigurer, "'codecConfigurer' is required");
	Assert.notNull(localeContextResolver, "'localeContextResolver' is required");

	// Initialize before first call to getLogPrefix()
	this.attributes.put(ServerWebExchange.LOG_ID_ATTRIBUTE, request.getId());

	this.request = request;
	this.response = response;
	this.sessionMono = sessionManager.getSession(this).cache();
	this.localeContextResolver = localeContextResolver;
	this.formDataMono = initFormData(request, codecConfigurer, getLogPrefix());
	this.multipartDataMono = initMultipartData(request, codecConfigurer, getLogPrefix());
	this.applicationContext = applicationContext;
}
 
Example #5
Source File: DefaultWebSessionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {

	when(this.createSession.save()).thenReturn(Mono.empty());
	when(this.createSession.getId()).thenReturn("create-session-id");
	when(this.updateSession.getId()).thenReturn("update-session-id");

	when(this.sessionStore.createWebSession()).thenReturn(Mono.just(this.createSession));
	when(this.sessionStore.retrieveSession(this.updateSession.getId())).thenReturn(Mono.just(this.updateSession));

	this.sessionManager = new DefaultWebSessionManager();
	this.sessionManager.setSessionIdResolver(this.sessionIdResolver);
	this.sessionManager.setSessionStore(this.sessionStore);

	MockServerHttpRequest request = MockServerHttpRequest.get("/path").build();
	MockServerHttpResponse response = new MockServerHttpResponse();
	this.exchange = new DefaultServerWebExchange(request, response, this.sessionManager,
			ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver());
}
 
Example #6
Source File: RequestMappingHandlerAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	Assert.notNull(this.applicationContext, "ApplicationContext is required");

	if (CollectionUtils.isEmpty(this.messageReaders)) {
		ServerCodecConfigurer codecConfigurer = ServerCodecConfigurer.create();
		this.messageReaders = codecConfigurer.getReaders();
	}
	if (this.argumentResolverConfigurer == null) {
		this.argumentResolverConfigurer = new ArgumentResolverConfigurer();
	}
	if (this.reactiveAdapterRegistry == null) {
		this.reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
	}

	this.methodResolver = new ControllerMethodResolver(this.argumentResolverConfigurer,
			this.reactiveAdapterRegistry, this.applicationContext, this.messageReaders);

	this.modelInitializer = new ModelInitializer(this.methodResolver, this.reactiveAdapterRegistry);
}
 
Example #7
Source File: DelegatingWebFluxConfigurationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	delegatingConfig.setConfigurers(Collections.singletonList(webFluxConfigurer));
	ReactiveAdapterRegistry reactiveAdapterRegistry = delegatingConfig.webFluxAdapterRegistry();
	ServerCodecConfigurer serverCodecConfigurer = delegatingConfig.serverCodecConfigurer();
	FormattingConversionService formattingConversionService = delegatingConfig.webFluxConversionService();
	Validator validator = delegatingConfig.webFluxValidator();

	ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)
			this.delegatingConfig.requestMappingHandlerAdapter(reactiveAdapterRegistry, serverCodecConfigurer,
					formattingConversionService, validator).getWebBindingInitializer();

	verify(webFluxConfigurer).configureHttpMessageCodecs(codecsConfigurer.capture());
	verify(webFluxConfigurer).getValidator();
	verify(webFluxConfigurer).getMessageCodesResolver();
	verify(webFluxConfigurer).addFormatters(formatterRegistry.capture());
	verify(webFluxConfigurer).configureArgumentResolvers(any());

	assertNotNull(initializer);
	assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
	assertSame(formatterRegistry.getValue(), initializer.getConversionService());
	assertEquals(13, codecsConfigurer.getValue().getReaders().size());
}
 
Example #8
Source File: NashornScriptTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // gh-22754
public void subscribeWithoutDemand() throws Exception {
	ZeroDemandResponse response = new ZeroDemandResponse();
	ServerWebExchange exchange = new DefaultServerWebExchange(
			MockServerHttpRequest.get("/path").build(), response,
			new DefaultWebSessionManager(), ServerCodecConfigurer.create(),
			new AcceptHeaderLocaleContextResolver());

	Map<String, Object> model = new HashMap<>();
	model.put("title", "Layout example");
	model.put("body", "This is the body");
	String viewUrl = "org/springframework/web/reactive/result/view/script/nashorn/template.html";
	ScriptTemplateView view = createViewWithUrl(viewUrl, ScriptTemplatingConfiguration.class);
	view.render(model, null, exchange).subscribe();

	response.cancelWrite();
	response.checkForLeaks();
}
 
Example #9
Source File: FreeMarkerViewTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // gh-22754
public void subscribeWithoutDemand() {
	ZeroDemandResponse response = new ZeroDemandResponse();
	ServerWebExchange exchange = new DefaultServerWebExchange(
			MockServerHttpRequest.get("/path").build(), response,
			new DefaultWebSessionManager(), ServerCodecConfigurer.create(),
			new AcceptHeaderLocaleContextResolver());

	FreeMarkerView view = new FreeMarkerView();
	view.setConfiguration(this.freeMarkerConfig);
	view.setUrl("test.ftl");

	ModelMap model = new ExtendedModelMap();
	model.addAttribute("hello", "hi FreeMarker");
	view.render(model, null, exchange).subscribe();

	response.cancelWrite();
	response.checkForLeaks();
}
 
Example #10
Source File: ControllerMethodResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setup() {
	ArgumentResolverConfigurer resolvers = new ArgumentResolverConfigurer();
	resolvers.addCustomResolver(new CustomArgumentResolver());
	resolvers.addCustomResolver(new CustomSyncArgumentResolver());

	ServerCodecConfigurer codecs = ServerCodecConfigurer.create();
	codecs.customCodecs().decoder(new ByteArrayDecoder());
	codecs.customCodecs().decoder(new ByteBufferDecoder());

	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
	applicationContext.registerBean(TestControllerAdvice.class);
	applicationContext.refresh();

	this.methodResolver = new ControllerMethodResolver(
			resolvers, ReactiveAdapterRegistry.getSharedInstance(), applicationContext, codecs.getReaders());

	Method method = ResolvableMethod.on(TestController.class).mockCall(TestController::handle).method();
	this.handlerMethod = new HandlerMethod(new TestController(), method);
}
 
Example #11
Source File: DefaultWebSessionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {

	given(this.createSession.save()).willReturn(Mono.empty());
	given(this.createSession.getId()).willReturn("create-session-id");
	given(this.updateSession.getId()).willReturn("update-session-id");

	given(this.sessionStore.createWebSession()).willReturn(Mono.just(this.createSession));
	given(this.sessionStore.retrieveSession(this.updateSession.getId())).willReturn(Mono.just(this.updateSession));

	this.sessionManager = new DefaultWebSessionManager();
	this.sessionManager.setSessionIdResolver(this.sessionIdResolver);
	this.sessionManager.setSessionStore(this.sessionStore);

	MockServerHttpRequest request = MockServerHttpRequest.get("/path").build();
	MockServerHttpResponse response = new MockServerHttpResponse();
	this.exchange = new DefaultServerWebExchange(request, response, this.sessionManager,
			ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver());
}
 
Example #12
Source File: DefaultServerWebExchange.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, Part>> initMultipartData(ServerHttpRequest request,
		ServerCodecConfigurer configurer, String logPrefix) {

	try {
		MediaType contentType = request.getHeaders().getContentType();
		if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) {
			return ((HttpMessageReader<MultiValueMap<String, Part>>) configurer.getReaders().stream()
					.filter(reader -> reader.canRead(MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA))
					.findFirst()
					.orElseThrow(() -> new IllegalStateException("No multipart HttpMessageReader.")))
					.readMono(MULTIPART_DATA_TYPE, request, Hints.from(Hints.LOG_PREFIX_HINT, logPrefix))
					.switchIfEmpty(EMPTY_MULTIPART_DATA)
					.cache();
		}
	}
	catch (InvalidMediaTypeException ex) {
		// Ignore
	}
	return EMPTY_MULTIPART_DATA;
}
 
Example #13
Source File: DefaultServerWebExchange.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, String>> initFormData(ServerHttpRequest request,
		ServerCodecConfigurer configurer, String logPrefix) {

	try {
		MediaType contentType = request.getHeaders().getContentType();
		if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
			return ((HttpMessageReader<MultiValueMap<String, String>>) configurer.getReaders().stream()
					.filter(reader -> reader.canRead(FORM_DATA_TYPE, MediaType.APPLICATION_FORM_URLENCODED))
					.findFirst()
					.orElseThrow(() -> new IllegalStateException("No form data HttpMessageReader.")))
					.readMono(FORM_DATA_TYPE, request, Hints.from(Hints.LOG_PREFIX_HINT, logPrefix))
					.switchIfEmpty(EMPTY_FORM_DATA)
					.cache();
		}
	}
	catch (InvalidMediaTypeException ex) {
		// Ignore
	}
	return EMPTY_FORM_DATA;
}
 
Example #14
Source File: DefaultControllerSpecTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void configurerConsumers() {
	TestConsumer<ArgumentResolverConfigurer> argumentResolverConsumer = new TestConsumer<>();
	TestConsumer<RequestedContentTypeResolverBuilder> contenTypeResolverConsumer = new TestConsumer<>();
	TestConsumer<CorsRegistry> corsRegistryConsumer = new TestConsumer<>();
	TestConsumer<FormatterRegistry> formatterConsumer = new TestConsumer<>();
	TestConsumer<ServerCodecConfigurer> codecsConsumer = new TestConsumer<>();
	TestConsumer<PathMatchConfigurer> pathMatchingConsumer = new TestConsumer<>();
	TestConsumer<ViewResolverRegistry> viewResolverConsumer = new TestConsumer<>();

	new DefaultControllerSpec(new MyController())
			.argumentResolvers(argumentResolverConsumer)
			.contentTypeResolver(contenTypeResolverConsumer)
			.corsMappings(corsRegistryConsumer)
			.formatters(formatterConsumer)
			.httpMessageCodecs(codecsConsumer)
			.pathMatching(pathMatchingConsumer)
			.viewResolvers(viewResolverConsumer)
			.build();

	assertNotNull(argumentResolverConsumer.getValue());
	assertNotNull(contenTypeResolverConsumer.getValue());
	assertNotNull(corsRegistryConsumer.getValue());
	assertNotNull(formatterConsumer.getValue());
	assertNotNull(codecsConsumer.getValue());
	assertNotNull(pathMatchingConsumer.getValue());
	assertNotNull(viewResolverConsumer.getValue());

}
 
Example #15
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 #16
Source File: SpringWebfluxApiExceptionHandlerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    projectApiErrorsMock = mock(ProjectApiErrors.class);
    listenerList = new SpringWebFluxApiExceptionHandlerListenerList(
        Arrays.asList(mock(ApiExceptionHandlerListener.class), mock(ApiExceptionHandlerListener.class))
    );
    generalUtils = ApiExceptionHandlerUtils.DEFAULT_IMPL;
    springUtilsMock = mock(SpringWebfluxApiExceptionHandlerUtils.class);
    viewResolversProviderMock = mock(ObjectProvider.class);
    serverCodecConfigurerMock = mock(ServerCodecConfigurer.class);
    messageReaders = Arrays.asList(mock(HttpMessageReader.class), mock(HttpMessageReader.class));
    messageWriters = Arrays.asList(mock(HttpMessageWriter.class), mock(HttpMessageWriter.class));
    viewResolvers = Arrays.asList(mock(ViewResolver.class), mock(ViewResolver.class));
    serverWebExchangeMock = mock(ServerWebExchange.class);
    serverHttpRequestMock = mock(ServerHttpRequest.class);
    serverHttpResponseMock = mock(ServerHttpResponse.class);
    serverHttpResponseHeadersMock = mock(HttpHeaders.class);
    uri = URI.create("http://localhost:8080/foo/bar?someQuery=someValue");
    exMock = mock(Throwable.class);

    doAnswer(invocation -> viewResolvers.stream()).when(viewResolversProviderMock).orderedStream();
    doReturn(messageReaders).when(serverCodecConfigurerMock).getReaders();
    doReturn(messageWriters).when(serverCodecConfigurerMock).getWriters();

    doReturn(serverHttpRequestMock).when(serverWebExchangeMock).getRequest();
    doReturn(uri).when(serverHttpRequestMock).getURI();

    doReturn(serverHttpResponseMock).when(serverWebExchangeMock).getResponse();
    doReturn(serverHttpResponseHeadersMock).when(serverHttpResponseMock).getHeaders();

    handlerSpy = spy(new SpringWebfluxApiExceptionHandler(
        projectApiErrorsMock, listenerList, generalUtils, springUtilsMock, viewResolversProviderMock,
        serverCodecConfigurerMock
    ));
}
 
Example #17
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 #18
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 #19
Source File: ErrorHandlerConfiguration.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new Error handler configuration.
 *
 * @param serverProperties      the server properties
 * @param resourceProperties    the resource properties
 * @param viewResolversProvider the view resolvers provider
 * @param serverCodecConfigurer the server codec configurer
 * @param applicationContext    the application context
 */
public ErrorHandlerConfiguration(final ServerProperties serverProperties,
                                 final ResourceProperties resourceProperties,
                                 final ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                 final ServerCodecConfigurer serverCodecConfigurer,
                                 final ApplicationContext applicationContext) {
    this.serverProperties = serverProperties;
    this.applicationContext = applicationContext;
    this.resourceProperties = resourceProperties;
    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    this.serverCodecConfigurer = serverCodecConfigurer;
}
 
Example #20
Source File: SpringWebfluxApiExceptionHandler.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Inject
public SpringWebfluxApiExceptionHandler(
    @NotNull ProjectApiErrors projectApiErrors,
    @NotNull SpringWebFluxApiExceptionHandlerListenerList apiExceptionHandlerListeners,
    @NotNull ApiExceptionHandlerUtils generalUtils,
    @NotNull SpringWebfluxApiExceptionHandlerUtils springUtils,
    @NotNull ObjectProvider<ViewResolver> viewResolversProvider,
    @NotNull ServerCodecConfigurer serverCodecConfigurer
) {
    super(projectApiErrors, apiExceptionHandlerListeners.listeners, generalUtils);

    //noinspection ConstantConditions
    if (springUtils == null) {
        throw new NullPointerException("springUtils cannot be null.");
    }

    //noinspection ConstantConditions
    if (viewResolversProvider == null) {
        throw new NullPointerException("viewResolversProvider cannot be null.");
    }

    //noinspection ConstantConditions
    if (serverCodecConfigurer == null) {
        throw new NullPointerException("serverCodecConfigurer cannot be null.");
    }

    this.springUtils = springUtils;
    this.viewResolvers = viewResolversProvider.orderedStream().collect(Collectors.toList());
    this.messageReaders = serverCodecConfigurer.getReaders();
    this.messageWriters = serverCodecConfigurer.getWriters();
}
 
Example #21
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 #22
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 #23
Source File: ReactiveWebServerInitializer.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
@Override
public ServerCodecConfigurer serverCodecConfigurer() {
	ServerCodecConfigurer configurer = ServerCodecConfigurer.create();
	configurer.registerDefaults(false);
	getApplicationContext().getBeanProvider(CodecCustomizer.class)
			.forEach((customizer) -> customizer.customize(configurer));
	return configurer;
}
 
Example #24
Source File: RequestPartMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	List<HttpMessageReader<?>> readers = ServerCodecConfigurer.create().getReaders();
	ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance();
	this.resolver = new RequestPartMethodArgumentResolver(readers, registry);

	List<HttpMessageWriter<?>> writers = ClientCodecConfigurer.create().getWriters();
	this.writer = new MultipartHttpMessageWriter(writers);
}
 
Example #25
Source File: DefaultControllerSpecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void configurerConsumers() {
	TestConsumer<ArgumentResolverConfigurer> argumentResolverConsumer = new TestConsumer<>();
	TestConsumer<RequestedContentTypeResolverBuilder> contenTypeResolverConsumer = new TestConsumer<>();
	TestConsumer<CorsRegistry> corsRegistryConsumer = new TestConsumer<>();
	TestConsumer<FormatterRegistry> formatterConsumer = new TestConsumer<>();
	TestConsumer<ServerCodecConfigurer> codecsConsumer = new TestConsumer<>();
	TestConsumer<PathMatchConfigurer> pathMatchingConsumer = new TestConsumer<>();
	TestConsumer<ViewResolverRegistry> viewResolverConsumer = new TestConsumer<>();

	new DefaultControllerSpec(new MyController())
			.argumentResolvers(argumentResolverConsumer)
			.contentTypeResolver(contenTypeResolverConsumer)
			.corsMappings(corsRegistryConsumer)
			.formatters(formatterConsumer)
			.httpMessageCodecs(codecsConsumer)
			.pathMatching(pathMatchingConsumer)
			.viewResolvers(viewResolverConsumer)
			.build();

	assertNotNull(argumentResolverConsumer.getValue());
	assertNotNull(contenTypeResolverConsumer.getValue());
	assertNotNull(corsRegistryConsumer.getValue());
	assertNotNull(formatterConsumer.getValue());
	assertNotNull(codecsConsumer.getValue());
	assertNotNull(pathMatchingConsumer.getValue());
	assertNotNull(viewResolverConsumer.getValue());

}
 
Example #26
Source File: HttpWebHandlerAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Configure a custom {@link ServerCodecConfigurer}. The provided instance is set on
 * each created {@link DefaultServerWebExchange}.
 * <p>By default this is set to {@link ServerCodecConfigurer#create()}.
 * @param codecConfigurer the codec configurer to use
 */
public void setCodecConfigurer(ServerCodecConfigurer codecConfigurer) {
	Assert.notNull(codecConfigurer, "ServerCodecConfigurer is required");
	this.codecConfigurer = codecConfigurer;

	this.enableLoggingRequestDetails = false;
	this.codecConfigurer.getReaders().stream()
			.filter(LoggingCodecSupport.class::isInstance)
			.forEach(reader -> {
				if (((LoggingCodecSupport) reader).isEnableLoggingRequestDetails()) {
					this.enableLoggingRequestDetails = true;
				}
			});
}
 
Example #27
Source File: FunctionEndpointInitializer.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
private DefaultErrorWebExceptionHandler errorHandler(GenericApplicationContext context) {
	context.registerBean(ErrorAttributes.class, () -> new DefaultErrorAttributes());
	context.registerBean(ErrorProperties.class, () -> new ErrorProperties());
	context.registerBean(ResourceProperties.class, () -> new ResourceProperties());
	DefaultErrorWebExceptionHandler handler = new DefaultErrorWebExceptionHandler(
			context.getBean(ErrorAttributes.class), context.getBean(ResourceProperties.class),
			context.getBean(ErrorProperties.class), context);
	ServerCodecConfigurer codecs = ServerCodecConfigurer.create();
	handler.setMessageWriters(codecs.getWriters());
	handler.setMessageReaders(codecs.getReaders());
	return handler;
}
 
Example #28
Source File: ReactiveWebServerInitializer.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean("webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class, WebServerFactoryCustomizerBeanPostProcessor::new);

	context.registerBean(ReactiveWebServerFactoryCustomizer.class, () -> new ReactiveWebServerFactoryCustomizer(this.serverProperties));
	context.registerBean(ConfigurableReactiveWebServerFactory.class, () -> serverFactory);
	//noinspection deprecation
	context.registerBean(ErrorAttributes.class, () -> new DefaultErrorAttributes(serverProperties.getError().isIncludeException()));
	context.registerBean(ErrorWebExceptionHandler.class,  () -> {
		ErrorWebFluxAutoConfiguration errorConfiguration = new ErrorWebFluxAutoConfiguration(this.serverProperties);
		return errorConfiguration.errorWebExceptionHandler(context.getBean(ErrorAttributes.class), this.resourceProperties, context.getBeanProvider(ViewResolver.class), context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class), context);
	});
	context.registerBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class, () -> new EnableWebFluxConfigurationWrapper(context, webFluxProperties));
	context.registerBean(LOCALE_CONTEXT_RESOLVER_BEAN_NAME, LocaleContextResolver.class, () -> context.getBean(EnableWebFluxConfigurationWrapper.class).localeContextResolver());
	context.registerBean("responseStatusExceptionHandler", WebExceptionHandler.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).responseStatusExceptionHandler());

	context.registerBean(RouterFunctionMapping.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).routerFunctionMapping(context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class)));
	context.registerBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).serverCodecConfigurer());
	context.registerBean("webFluxAdapterRegistry", ReactiveAdapterRegistry.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxAdapterRegistry());
	context.registerBean("handlerFunctionAdapter", HandlerFunctionAdapter.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).handlerFunctionAdapter());
	context.registerBean("webFluxContentTypeResolver", RequestedContentTypeResolver.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxContentTypeResolver());
	context.registerBean("webFluxConversionService", FormattingConversionService.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxConversionService());
	context.registerBean("serverResponseResultHandler", ServerResponseResultHandler.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).serverResponseResultHandler(context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class)));
	context.registerBean("simpleHandlerAdapter", SimpleHandlerAdapter.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).simpleHandlerAdapter());
	context.registerBean("viewResolutionResultHandler", ViewResolutionResultHandler.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).viewResolutionResultHandler(context.getBean("webFluxAdapterRegistry", ReactiveAdapterRegistry.class), context.getBean("webFluxContentTypeResolver", RequestedContentTypeResolver.class)));
	context.registerBean("webFluxValidator", Validator.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxValidator());
	context.registerBean(HttpHandler.class, () -> applicationContext(context).build());
	context.registerBean(WEB_HANDLER_BEAN_NAME, DispatcherHandler.class, (Supplier<DispatcherHandler>) DispatcherHandler::new);
	context.registerBean(WebFluxConfig.class, () -> new WebFluxConfig(resourceProperties, webFluxProperties, context, context.getBeanProvider(HandlerMethodArgumentResolver.class), context.getBeanProvider(CodecCustomizer.class),
		context.getBeanProvider(ResourceHandlerRegistrationCustomizer.class), context.getBeanProvider(ViewResolver.class)));
}
 
Example #29
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 #30
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;
}