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

The following examples show how to use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter. 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: DelegatingWebMvcConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: MvcNamespaceTests.java    From spring-analysis-note with 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 #3
Source File: MvcNamespaceTests.java    From spring-analysis-note with 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 #4
Source File: MvcNamespaceTests.java    From spring-analysis-note with 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 #5
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: JobExecutionUtils.java    From spring-cloud-dataflow with 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 #7
Source File: WebMvcConfigurationSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #8
Source File: DelegatingWebMvcConfigurationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #9
Source File: WebMvcConfig.java    From example-restful-project with 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 #10
Source File: MvcNamespaceTests.java    From spring4-understanding with 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 #11
Source File: MvcNamespaceTests.java    From spring4-understanding with 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 #12
Source File: ColaConfiguration.java    From bdf3 with 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 #13
Source File: SbpMvcPatchAutoConfiguration.java    From sbp with 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 #14
Source File: MvcNamespaceTests.java    From java-technology-stack with 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 #15
Source File: MvcNamespaceTests.java    From java-technology-stack with 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 #16
Source File: MvcNamespaceTests.java    From java-technology-stack with 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 #17
Source File: WebMvcConfigurationSupportExtensionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #18
Source File: RaptorHandlerAdapterPostProcessor.java    From raptor with 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 #19
Source File: WebMvcConfigurationSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #20
Source File: AbstractRender.java    From Aooms with 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 #21
Source File: SpringMvcConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Bean
public List<HandlerMethodReturnValueHandler> returnValueHandlers(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
    final List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(requestMappingHandlerAdapter.getReturnValueHandlers());
    handlers.add(0, new ObserableReturnValueHandler());
    handlers.add(0, new ListenableFutureReturnValueHandler());
    requestMappingHandlerAdapter.setReturnValueHandlers(handlers);
    return handlers;
}
 
Example #22
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageConverters() {
	loadBeanDefinitions("mvc-config-message-converters.xml");
	verifyMessageConverters(appContext.getBean(RequestMappingHandlerAdapter.class), true);
	verifyMessageConverters(appContext.getBean(ExceptionHandlerExceptionResolver.class), true);
	verifyRequestResponseBodyAdvice(appContext.getBean(RequestMappingHandlerAdapter.class));
	verifyResponseBodyAdvice(appContext.getBean(ExceptionHandlerExceptionResolver.class));
}
 
Example #23
Source File: WebMvcConfigurationSupport.java    From spring4-understanding with Apache License 2.0 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() {
	List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<HandlerMethodArgumentResolver>();
	addArgumentResolvers(argumentResolvers);

	List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<HandlerMethodReturnValueHandler>();
	addReturnValueHandlers(returnValueHandlers);

	RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
	adapter.setContentNegotiationManager(mvcContentNegotiationManager());
	adapter.setMessageConverters(getMessageConverters());
	adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer());
	adapter.setCustomArgumentResolvers(argumentResolvers);
	adapter.setCustomReturnValueHandlers(returnValueHandlers);

	if (jackson2Present) {
		List<RequestBodyAdvice> requestBodyAdvices = new ArrayList<RequestBodyAdvice>();
		requestBodyAdvices.add(new JsonViewRequestBodyAdvice());
		adapter.setRequestBodyAdvice(requestBodyAdvices);

		List<ResponseBodyAdvice<?>> responseBodyAdvices = new ArrayList<ResponseBodyAdvice<?>>();
		responseBodyAdvices.add(new JsonViewResponseBodyAdvice());
		adapter.setResponseBodyAdvice(responseBodyAdvices);
	}

	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 #24
Source File: WebMvcConfigurationSupportExtensionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: RaptorHandlerAdapterPostProcessor.java    From raptor with Apache License 2.0 5 votes vote down vote up
private List<Object> getRequestResponseBodyAdviceByReflect(RequestMappingHandlerAdapter adapter) {
    try {
        Field field = adapter.getClass().getDeclaredField("requestResponseBodyAdvice");
        //设置对象的访问权限,保证对private的属性的访问
        field.setAccessible(true);
        return (List<Object>) field.get(adapter);
    } catch (Exception e) {
        log.warn("getRequestResponseBodyAdviceByReflect failed :" + e.getMessage());
        return new ArrayList<>();
    }
}
 
Example #26
Source File: StandaloneMockMvcBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void registerMvcSingletons(StubWebApplicationContext wac) {
	StandaloneConfiguration config = new StandaloneConfiguration();
	config.setApplicationContext(wac);

	wac.addBeans(this.controllerAdvice);

	StaticRequestMappingHandlerMapping hm = config.getHandlerMapping();
	hm.setServletContext(wac.getServletContext());
	hm.setApplicationContext(wac);
	hm.afterPropertiesSet();
	hm.registerHandlers(this.controllers);
	wac.addBean("requestMappingHandlerMapping", hm);

	RequestMappingHandlerAdapter handlerAdapter = config.requestMappingHandlerAdapter();
	handlerAdapter.setServletContext(wac.getServletContext());
	handlerAdapter.setApplicationContext(wac);
	handlerAdapter.afterPropertiesSet();
	wac.addBean("requestMappingHandlerAdapter", handlerAdapter);

	wac.addBean("handlerExceptionResolver", config.handlerExceptionResolver());

	wac.addBeans(initViewResolvers(wac));
	wac.addBean(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, this.localeResolver);
	wac.addBean(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, new FixedThemeResolver());
	wac.addBean(DispatcherServlet.REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, new DefaultRequestToViewNameTranslator());

	this.flashMapManager = new SessionFlashMapManager();
	wac.addBean(DispatcherServlet.FLASH_MAP_MANAGER_BEAN_NAME, this.flashMapManager);
}
 
Example #27
Source File: MessageConverterAddingPostProcessor.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization( Object bean, String beanName )
    throws BeansException
{
    if ( !(bean instanceof RequestMappingHandlerAdapter) )
    {
        return bean;
    }

    RequestMappingHandlerAdapter handlerAdapter = (RequestMappingHandlerAdapter) bean;
    List<HttpMessageConverter<?>> converters = handlerAdapter.getMessageConverters();
    converters.add( 0, messageConverter );
    handlerAdapter.setMessageConverters( converters );
    return handlerAdapter;
}
 
Example #28
Source File: WebapiApplicationRunListener.java    From summerframework with Apache License 2.0 5 votes vote down vote up
/**
 * 反射获取HandlerMethodReturnValueHandler集合
 */
private List<HandlerMethodReturnValueHandler>
    findHandlerMethodReturnValueHandlers(RequestMappingHandlerAdapter requestMappingHandlerAdapter)
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    Field returnValueHandlerCompositeField =
        ReflectionUtils.findField(RequestMappingHandlerAdapter.class, "returnValueHandlers");
    returnValueHandlerCompositeField.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(returnValueHandlerCompositeField,
        returnValueHandlerCompositeField.getModifiers() & ~Modifier.FINAL);
    HandlerMethodReturnValueHandlerComposite returnValueHandlerComposite =
        (HandlerMethodReturnValueHandlerComposite)ReflectionUtils.getField(returnValueHandlerCompositeField,
            requestMappingHandlerAdapter);
    Field returnValueHandlersField =
        ReflectionUtils.findField(HandlerMethodReturnValueHandlerComposite.class, "returnValueHandlers");
    returnValueHandlersField.setAccessible(true);
    Field returnValueHandlerModifiersField = Field.class.getDeclaredField("modifiers");
    returnValueHandlerModifiersField.setAccessible(true);
    returnValueHandlerModifiersField.setInt(returnValueHandlersField,
        returnValueHandlersField.getModifiers() & ~Modifier.FINAL);
    List<HandlerMethodReturnValueHandler> returnValueHandlers =
        (List<HandlerMethodReturnValueHandler>)ReflectionUtils.getField(returnValueHandlersField,
            returnValueHandlerComposite);
    return returnValueHandlers;

}
 
Example #29
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageCodesResolver() {
	loadBeanDefinitions("mvc-config-message-codes-resolver.xml");
	RequestMappingHandlerAdapter adapter = 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 #30
Source File: StandaloneMockMvcBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void registerMvcSingletons(StubWebApplicationContext wac) {
	StandaloneConfiguration config = new StandaloneConfiguration();
	config.setApplicationContext(wac);
	ServletContext sc = wac.getServletContext();

	wac.addBeans(this.controllers);
	wac.addBeans(this.controllerAdvice);

	RequestMappingHandlerMapping hm = config.getHandlerMapping();
	if (sc != null) {
		hm.setServletContext(sc);
	}
	hm.setApplicationContext(wac);
	hm.afterPropertiesSet();
	wac.addBean("requestMappingHandlerMapping", hm);

	RequestMappingHandlerAdapter ha = config.requestMappingHandlerAdapter();
	if (sc != null) {
		ha.setServletContext(sc);
	}
	ha.setApplicationContext(wac);
	ha.afterPropertiesSet();
	wac.addBean("requestMappingHandlerAdapter", ha);

	wac.addBean("handlerExceptionResolver", config.handlerExceptionResolver());

	wac.addBeans(initViewResolvers(wac));
	wac.addBean(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, this.localeResolver);
	wac.addBean(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, new FixedThemeResolver());
	wac.addBean(DispatcherServlet.REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, new DefaultRequestToViewNameTranslator());

	this.flashMapManager = new SessionFlashMapManager();
	wac.addBean(DispatcherServlet.FLASH_MAP_MANAGER_BEAN_NAME, this.flashMapManager);

	extendMvcSingletons(sc).forEach(wac::addBean);
}