Java Code Examples for org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

The following examples show how to use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter. 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
Source Project: spring-analysis-note   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml");

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(1, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
	interceptor.preHandle(request, response, handler);
	assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	adapter.handle(request, response, handlerMethod);
}
 
Example 2
Source Project: spring-analysis-note   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
private void doTestCustomValidator(String xml) throws Exception {
	loadBeanDefinitions(xml);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent());

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();
	adapter.handle(request, response, handlerMethod);

	assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
	assertFalse(handler.recordedValidationError);
}
 
Example 3
Source Project: spring-analysis-note   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testAsyncSupportOptions() throws Exception {
	loadBeanDefinitions("mvc-config-async-support.xml");

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);
}
 
Example 4
@Test
public void customArgumentResolvers() {
	ApplicationContext context = initContext(CustomArgumentResolverConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	HandlerExceptionResolverComposite composite = context.getBean(HandlerExceptionResolverComposite.class);

	assertNotNull(adapter);
	assertEquals(1, adapter.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, adapter.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, adapter.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, adapter.getCustomReturnValueHandlers().get(0).getClass());

	assertNotNull(composite);
	assertEquals(3, composite.getExceptionResolvers().size());
	assertEquals(ExceptionHandlerExceptionResolver.class, composite.getExceptionResolvers().get(0).getClass());

	ExceptionHandlerExceptionResolver resolver =
			(ExceptionHandlerExceptionResolver) composite.getExceptionResolvers().get(0);

	assertEquals(1, resolver.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, resolver.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, resolver.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, resolver.getCustomReturnValueHandlers().get(0).getClass());
}
 
Example 5
@Test
public void requestMappingHandlerAdapter() throws Exception {
	delegatingConfig.setConfigurers(Collections.singletonList(webMvcConfigurer));
	RequestMappingHandlerAdapter adapter = this.delegatingConfig.requestMappingHandlerAdapter(
			this.delegatingConfig.mvcContentNegotiationManager(), this.delegatingConfig.mvcConversionService(),
			this.delegatingConfig.mvcValidator());

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();

	verify(webMvcConfigurer).configureMessageConverters(converters.capture());
	verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture());
	verify(webMvcConfigurer).addFormatters(conversionService.capture());
	verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture());
	verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture());
	verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture());

	assertNotNull(initializer);
	assertSame(conversionService.getValue(), initializer.getConversionService());
	assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
	assertEquals(0, resolvers.getValue().size());
	assertEquals(0, handlers.getValue().size());
	assertEquals(converters.getValue(), adapter.getMessageConverters());
	assertNotNull(asyncConfigurer);
}
 
Example 6
Source Project: sbp   Source File: SbpMvcPatchAutoConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(WebMvcRegistrations.class)
public WebMvcRegistrations mvcRegistrations() {
	return new WebMvcRegistrations() {
		@Override
		public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
			return new PluginRequestMappingHandlerMapping();
		}

		@Override
		public RequestMappingHandlerAdapter getRequestMappingHandlerAdapter() {
			return null;
		}

		@Override
		public ExceptionHandlerExceptionResolver getExceptionHandlerExceptionResolver() {
			return null;
		}
	};
}
 
Example 7
Source Project: java-technology-stack   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml");

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(1, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
	interceptor.preHandle(request, response, handler);
	assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	adapter.handle(request, response, handlerMethod);
}
 
Example 8
Source Project: java-technology-stack   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
private void doTestCustomValidator(String xml) throws Exception {
	loadBeanDefinitions(xml);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent());

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();
	adapter.handle(request, response, handlerMethod);

	assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
	assertFalse(handler.recordedValidationError);
}
 
Example 9
Source Project: java-technology-stack   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testAsyncSupportOptions() throws Exception {
	loadBeanDefinitions("mvc-config-async-support.xml");

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);
}
 
Example 10
@Test
public void webBindingInitializer() throws Exception {
	RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter();

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();

	assertNotNull(initializer);

	BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, "");
	initializer.getValidator().validate(null, bindingResult);
	assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode());

	String[] codes = initializer.getMessageCodesResolver().resolveMessageCodes("invalid", null);
	assertEquals("custom.invalid", codes[0]);
}
 
Example 11
@Test
public void customArgumentResolvers() {
	ApplicationContext context = initContext(CustomArgumentResolverConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	HandlerExceptionResolverComposite composite = context.getBean(HandlerExceptionResolverComposite.class);

	assertNotNull(adapter);
	assertEquals(1, adapter.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, adapter.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, adapter.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, adapter.getCustomReturnValueHandlers().get(0).getClass());

	assertNotNull(composite);
	assertEquals(3, composite.getExceptionResolvers().size());
	assertEquals(ExceptionHandlerExceptionResolver.class, composite.getExceptionResolvers().get(0).getClass());

	ExceptionHandlerExceptionResolver resolver =
			(ExceptionHandlerExceptionResolver) composite.getExceptionResolvers().get(0);

	assertEquals(1, resolver.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, resolver.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, resolver.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, resolver.getCustomReturnValueHandlers().get(0).getClass());
}
 
Example 12
Source Project: Aooms   Source File: AbstractRender.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * springmvc提供的render方法
 *
 */
public void springMvcRender(Object returnValue){
    try{
        // modelAndViewContainer init
        ModelAndViewContainer modelAndViewContainer = new ModelAndViewContainer();
        ServletWebRequest webRequest = new ServletWebRequest(AoomsContext.getRequest(), AoomsContext.getResponse());

        // get ApplicationContext
        ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(AoomsContext.getServletContext());

        // get RequestMappingHandlerAdapter Bean
        RequestMappingHandlerAdapter requestMappingHandlerAdapter = (RequestMappingHandlerAdapter)ac1.getBean("requestMappingHandlerAdapter");

        // init handlerMethodReturnValueHandlerComposite
        HandlerMethodReturnValueHandlerComposite handlerMethodReturnValueHandlerComposite = new HandlerMethodReturnValueHandlerComposite();
        handlerMethodReturnValueHandlerComposite.addHandlers(requestMappingHandlerAdapter.getReturnValueHandlers());

        // render
        HandlerMethod method = AoomsContext.getMethodHandler();
        handlerMethodReturnValueHandlerComposite.handleReturnValue(returnValue, method.getReturnType(), modelAndViewContainer, webRequest);

    } catch (Exception ex){
        throw AoomsExceptions.create("springmvc render error",ex);
    }
}
 
Example 13
Source Project: raptor   Source File: RaptorHandlerAdapterPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (RequestMappingHandlerAdapter.class.isAssignableFrom(ClassUtils.getUserClass(bean))) {
        RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter) bean;
        List<Object> advices = getRequestResponseBodyAdviceByReflect(adapter);
        RaptorHandlerMethodProcessor raptorHandlerMethodProcessor = new RaptorHandlerMethodProcessor(raptorMessageConverter,advices);

        ArrayList<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(adapter.getArgumentResolvers());
        argumentResolvers.add(0, raptorHandlerMethodProcessor);
        adapter.setArgumentResolvers(argumentResolvers);

        ArrayList<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<>(adapter.getReturnValueHandlers());
        returnValueHandlers.add(0, raptorHandlerMethodProcessor);
        adapter.setReturnValueHandlers(returnValueHandlers);
    }
    return bean;
}
 
Example 14
Source Project: bdf3   Source File: ColaConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void afterPropertiesSet() throws Exception {
	if (adapter != null) {
		Field field = ReflectionUtils.findField(RequestMappingHandlerAdapter.class, "contentNegotiationManager");
		field.setAccessible(true);
		ContentNegotiationManager contentNegotiationManager = (org.springframework.web.accept.ContentNegotiationManager) field.get(adapter);
		field = ReflectionUtils.findField(RequestMappingHandlerAdapter.class, "requestResponseBodyAdvice");
		field.setAccessible(true);
		List<Object> requestResponseBodyAdvice = (List<Object>) field.get(adapter);
		
		List<HandlerMethodReturnValueHandler> handlers = adapter.getReturnValueHandlers();
		List<HandlerMethodReturnValueHandler> result = new ArrayList<HandlerMethodReturnValueHandler>();
		for (HandlerMethodReturnValueHandler handler : handlers) {
			if (handler instanceof RequestResponseBodyMethodProcessor) {
				result.add(new RequestResponseBodyMethodProcessorAdapter(adapter.getMessageConverters(), contentNegotiationManager, requestResponseBodyAdvice));
			} else {
				result.add(handler);
			}
		}
		adapter.setReturnValueHandlers(result);
	}
}
 
Example 15
Source Project: spring4-understanding   Source File: MvcNamespaceTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
	loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 14);

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	assertNotNull(mapping);
	mapping.setDefaultHandler(handlerMethod);

	// default web binding initializer behavior test
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
	request.setRequestURI("/accounts/12345");
	request.addParameter("date", "2009-10-31");
	MockHttpServletResponse response = new MockHttpServletResponse();

	HandlerExecutionChain chain = mapping.getHandler(request);
	assertEquals(1, chain.getInterceptors().length);
	assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
	ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
	interceptor.preHandle(request, response, handler);
	assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	adapter.handle(request, response, handlerMethod);
}
 
Example 16
Source Project: spring4-understanding   Source File: MvcNamespaceTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncSupportOptions() throws Exception {
	loadBeanDefinitions("mvc-config-async-support.xml", 15);

	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass());
	assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout"));

	CallableProcessingInterceptor[] callableInterceptors =
			(CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors");
	assertEquals(1, callableInterceptors.length);

	DeferredResultProcessingInterceptor[] deferredResultInterceptors =
			(DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors");
	assertEquals(1, deferredResultInterceptors.length);
}
 
Example 17
@Test
public void requestMappingHandlerAdapter() throws Exception {

	delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer));
	RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter();

	ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	ConversionService initializerConversionService = initializer.getConversionService();
	assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);

	verify(webMvcConfigurer).configureMessageConverters(converters.capture());
	verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture());
	verify(webMvcConfigurer).addFormatters(conversionService.capture());
	verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture());
	verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture());
	verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture());

	assertSame(conversionService.getValue(), initializerConversionService);
	assertEquals(0, resolvers.getValue().size());
	assertEquals(0, handlers.getValue().size());
	assertEquals(converters.getValue(), adapter.getMessageConverters());
	assertNotNull(asyncConfigurer);
}
 
Example 18
@SuppressWarnings("unchecked")
@Test
public void testArgumentResolvers() {
	loadBeanDefinitions("mvc-config-argument-resolvers.xml");
	RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	Object value = new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers");
	assertNotNull(value);
	assertTrue(value instanceof List);
	List<HandlerMethodArgumentResolver> resolvers = (List<HandlerMethodArgumentResolver>) value;
	assertEquals(3, resolvers.size());
	assertTrue(resolvers.get(0) instanceof ServletWebArgumentResolverAdapter);
	assertTrue(resolvers.get(1) instanceof TestHandlerMethodArgumentResolver);
	assertTrue(resolvers.get(2) instanceof TestHandlerMethodArgumentResolver);
	assertNotSame(resolvers.get(1), resolvers.get(2));
}
 
Example 19
Source Project: spring-cloud-dataflow   Source File: JobExecutionUtils.java    License: Apache License 2.0 6 votes vote down vote up
static MockMvc createBaseJobExecutionMockMvc(JobRepository jobRepository, TaskBatchDao taskBatchDao,
		TaskExecutionDao taskExecutionDao, WebApplicationContext wac, RequestMappingHandlerAdapter adapter) {
	MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac)
			.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON)).build();
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_ORIG, 1);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FOO, 1);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FOOBAR, 2);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_COMPLETED, 1, BatchStatus.COMPLETED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_STARTED, 1, BatchStatus.STARTED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_STOPPED, 1, BatchStatus.STOPPED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FAILED1, 1, BatchStatus.FAILED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FAILED2, 1, BatchStatus.FAILED);
	for (HttpMessageConverter<?> converter : adapter.getMessageConverters()) {
		if (converter instanceof MappingJackson2HttpMessageConverter) {
			final MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
			jacksonConverter.getObjectMapper().addMixIn(StepExecution.class, StepExecutionJacksonMixIn.class);
			jacksonConverter.getObjectMapper().addMixIn(ExecutionContext.class, ExecutionContextJacksonMixIn.class);
			jacksonConverter.getObjectMapper().setDateFormat(new ISO8601DateFormatWithMilliSeconds());
		}
	}
	return mockMvc;
}
 
Example 20
Source Project: example-restful-project   Source File: WebMvcConfig.java    License: MIT License 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ContextRefreshedEvent) {
        ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
        RequestMappingHandlerAdapter adapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);

        TeapotMappingHandler handler = new TeapotMappingHandler(
                mapper, getMessageConverters());

        List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
        argumentResolvers.add(handler);
        argumentResolvers.addAll(adapter.getArgumentResolvers());

        adapter.setArgumentResolvers(argumentResolvers);

        List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>();
        handlers.add(handler);  // must be first
        handlers.addAll(adapter.getReturnValueHandlers());

        adapter.setReturnValueHandlers(handlers);
    }
}
 
Example 21
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a {@link RequestMappingHandlerAdapter} for processing requests
 * through annotated controller methods. Consider overriding one of these
 * other more fine-grained methods:
 * <ul>
 * <li>{@link #addArgumentResolvers} for adding custom argument resolvers.
 * <li>{@link #addReturnValueHandlers} for adding custom return value handlers.
 * <li>{@link #configureMessageConverters} for adding custom message converters.
 * </ul>
 */
@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(
		ContentNegotiationManager mvcContentNegotiationManager,
		FormattingConversionService mvcConversionService,
		Validator mvcValidator) {
	RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();
	adapter.setContentNegotiationManager(mvcContentNegotiationManager);
	adapter.setMessageConverters(getMessageConverters());
	adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer(mvcConversionService, mvcValidator));
	adapter.setCustomArgumentResolvers(getArgumentResolvers());
	adapter.setCustomReturnValueHandlers(getReturnValueHandlers());

	if (jackson2Present) {
		adapter.setRequestBodyAdvice(Collections.singletonList(new JsonViewRequestBodyAdvice()));
		adapter.setResponseBodyAdvice(Collections.singletonList(new JsonViewResponseBodyAdvice()));
	}

	AsyncSupportConfigurer configurer = new AsyncSupportConfigurer();
	configureAsyncSupport(configurer);
	if (configurer.getTaskExecutor() != null) {
		adapter.setTaskExecutor(configurer.getTaskExecutor());
	}
	if (configurer.getTimeout() != null) {
		adapter.setAsyncRequestTimeout(configurer.getTimeout());
	}
	adapter.setCallableInterceptors(configurer.getCallableInterceptors());
	adapter.setDeferredResultInterceptors(configurer.getDeferredResultInterceptors());

	return adapter;
}
 
Example 22
Source Project: data-prep   Source File: Async.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RequestMappingHandlerAdapter doWith(RequestMappingHandlerAdapter handlerAdapter, String beanName,
        ApplicationContext applicationContext) {
    final AsyncTaskExecutor executor = (AsyncTaskExecutor) applicationContext.getBean(EXECUTOR);
    handlerAdapter.setTaskExecutor(executor);
    return handlerAdapter;
}
 
Example 23
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Return an instance of {@link CompositeUriComponentsContributor} for use with
 * {@link org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder}.
 * @since 4.0
 */
@Bean
public CompositeUriComponentsContributor mvcUriComponentsContributor(
		FormattingConversionService mvcConversionService,
		RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
	return new CompositeUriComponentsContributor(
			requestMappingHandlerAdapter.getArgumentResolvers(), mvcConversionService);
}
 
Example 24
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(12, converters.size());
	converters.stream()
			.filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter)
			.forEach(converter -> {
				ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
				assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
				if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
					assertEquals(XmlMapper.class, mapper.getClass());
				}
			});

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
 
Example 25
@Test
public void testMessageCodesResolver() {
	loadBeanDefinitions("mvc-config-message-codes-resolver.xml");
	RequestMappingHandlerAdapter adapter = this.appContext.getBean(RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);
	Object initializer = adapter.getWebBindingInitializer();
	assertNotNull(initializer);
	MessageCodesResolver resolver =
			((ConfigurableWebBindingInitializer) initializer).getMessageCodesResolver();
	assertNotNull(resolver);
	assertEquals(TestMessageCodesResolver.class, resolver.getClass());
	assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
}
 
Example 26
@Test
public void testMessageConverters() {
	loadBeanDefinitions("mvc-config-message-converters.xml");
	verifyMessageConverters(this.appContext.getBean(RequestMappingHandlerAdapter.class), true);
	verifyMessageConverters(this.appContext.getBean(ExceptionHandlerExceptionResolver.class), true);
	verifyRequestResponseBodyAdvice(this.appContext.getBean(RequestMappingHandlerAdapter.class));
	verifyResponseBodyAdvice(this.appContext.getBean(ExceptionHandlerExceptionResolver.class));
}
 
Example 27
Source Project: Milkomeda   Source File: CometCollectorConfig.java    License: MIT License 5 votes vote down vote up
@Autowired
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public void configResponseBodyAdvice(RequestMappingHandlerAdapter adapter, HandlerExceptionResolver handlerExceptionResolver) {
    if (!props.isEnableTag()) {
        return;
    }
    CometCollectorResponseBodyAdvice collectorResponseBodyAdvice = cometResponseBodyAdvice();
    // 动态添加到响应处理
    SpringMvcPolyfill.addDynamicResponseBodyAdvice(adapter.getReturnValueHandlers(), handlerExceptionResolver, collectorResponseBodyAdvice);
}
 
Example 28
Source Project: Milkomeda   Source File: CometConfig.java    License: MIT License 5 votes vote down vote up
@Autowired
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public void configParamResolve(RequestMappingHandlerAdapter adapter) {
    List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
    // 动态添加针对注解 @CometParam 处理的解析器
    argumentResolvers.add(new CometParamResolver());
    argumentResolvers.addAll(Objects.requireNonNull(adapter.getArgumentResolvers()));
    adapter.setArgumentResolvers(argumentResolvers);
}
 
Example 29
Source Project: yue-library   Source File: CustomArgumentResolversConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public void prioritizeCustomMethodArgumentHandlers(RequestMappingHandlerAdapter adapter) {
	List<HandlerMethodArgumentResolver> prioritizeCustomArgumentResolvers = new ArrayList<>();
	prioritizeCustomArgumentResolvers.add(new JSONObjectArgumentResolver());
	prioritizeCustomArgumentResolvers.addAll(adapter.getArgumentResolvers());
	adapter.setArgumentResolvers(prioritizeCustomArgumentResolvers);
}
 
Example 30
Source Project: tools   Source File: ExcelDrivenConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    RequestMappingHandlerAdapter handlerAdapter = this.applicationContext.getBean(RequestMappingHandlerAdapter.class);
    List<HandlerMethodReturnValueHandler> returnValueHandlers = handlerAdapter.getReturnValueHandlers();
    List<HandlerMethodReturnValueHandler> valueHandlers = new ArrayList<>();
    valueHandlers.add(new ExcelDrivenWriteHandler());
    valueHandlers.add(new ExcelDrivenReadHandler());
    if (returnValueHandlers != null) {
        valueHandlers.addAll(returnValueHandlers);
    }
    handlerAdapter.setReturnValueHandlers(valueHandlers);
}