下面列出了怎么用org.springframework.http.codec.ServerCodecConfigurer的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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());
}
@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();
}
@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();
}
@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);
}
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;
}
@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;
}
@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;
}
@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());
}
@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);
}
@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);
}
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;
}
@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());
}
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;
}
@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;
}
private void registerEndpoint(GenericApplicationContext context) {
context.registerBean(StringConverter.class,
() -> new BasicStringConverter(context.getBean(FunctionInspector.class), context.getBeanFactory()));
context.registerBean(RequestProcessor.class,
() -> new RequestProcessor(context.getBean(FunctionInspector.class),
context.getBean(FunctionCatalog.class), context.getBeanProvider(JsonMapper.class),
context.getBean(StringConverter.class), context.getBeanProvider(ServerCodecConfigurer.class)));
context.registerBean(PublicFunctionEndpointFactory.class,
() -> new PublicFunctionEndpointFactory(context.getBean(FunctionCatalog.class),
context.getBean(FunctionInspector.class), context.getBean(RequestProcessor.class),
context.getEnvironment()));
context.registerBean(RouterFunction.class,
() -> context.getBean(PublicFunctionEndpointFactory.class).functionEndpoints());
}
public GlobalErrorWebFluxConfiguration(
ApplicationContext applicationContext,
ResourceProperties resourceProperties,
List<ViewResolver> viewResolvers,
ServerCodecConfigurer serverCodecConfigurer
) {
this.applicationContext = applicationContext;
this.resourceProperties = resourceProperties;
this.viewResolvers = viewResolvers;
this.serverCodecConfigurer = serverCodecConfigurer;
}
@Primary
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
JsonExceptionHandler jsonExceptionHandler = new JsonExceptionHandler();
jsonExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
jsonExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
jsonExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
return jsonExceptionHandler;
}
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;
}
@Bean
public RouterFunctionMapping routerFunctionMapping(ServerCodecConfigurer serverCodecConfigurer) {
RouterFunctionMapping mapping = createRouterFunctionMapping();
mapping.setOrder(-1); // go before RequestMappingHandlerMapping
mapping.setMessageReaders(serverCodecConfigurer.getReaders());
mapping.setCorsConfigurations(getCorsConfigurations());
return mapping;
}
@Inject
public SpringWebfluxUnhandledExceptionHandler(
@NotNull ProjectApiErrors projectApiErrors,
@NotNull ApiExceptionHandlerUtils generalUtils,
@NotNull SpringWebfluxApiExceptionHandlerUtils springUtils,
@NotNull ObjectProvider<ViewResolver> viewResolversProvider,
@NotNull ServerCodecConfigurer serverCodecConfigurer
) {
super(projectApiErrors, 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.singletonGenericServiceError = Collections.singleton(projectApiErrors.getGenericServiceError());
this.genericServiceErrorHttpStatusCode = projectApiErrors.getGenericServiceError().getHttpStatusCode();
this.springUtils = springUtils;
this.viewResolvers = viewResolversProvider.orderedStream().collect(Collectors.toList());
this.messageReaders = serverCodecConfigurer.getReaders();
this.messageWriters = serverCodecConfigurer.getWriters();
}
/**
* 自定义异常处理,替换 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;
}
@Bean
public ResponseBodyResultHandler responseBodyResultHandler(
ReactiveAdapterRegistry webFluxAdapterRegistry,
ServerCodecConfigurer serverCodecConfigurer,
RequestedContentTypeResolver webFluxContentTypeResolver) {
return new ResponseBodyResultHandler(serverCodecConfigurer.getWriters(),
webFluxContentTypeResolver, webFluxAdapterRegistry);
}
public RequestProcessor(FunctionInspector inspector,
FunctionCatalog functionCatalog,
ObjectProvider<JsonMapper> mapper, StringConverter converter,
ObjectProvider<ServerCodecConfigurer> codecs) {
this.mapper = mapper.getIfAvailable();
this.inspector = inspector;
this.functionCatalog = functionCatalog;
this.converter = converter;
ServerCodecConfigurer source = codecs.getIfAvailable();
this.messageReaders = source == null ? null : source.getReaders();
}
@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);
}
/**
* 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;
}
});
}
@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());
}
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;
}
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;
}
/**
* 自定义异常处理
*/
@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;
}