Java Code Examples for org.springframework.web.accept.ContentNegotiationManager

The following examples show how to use org.springframework.web.accept.ContentNegotiationManager. 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
@Test  // SPR-14577
public void getMediaTypeWithFavorPathExtensionOff() throws Exception {
	ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean();
	factory.setFavorPathExtension(false);
	factory.afterPropertiesSet();
	ContentNegotiationManager manager = factory.getObject();

	List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass()));
	ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
	handler.setServletContext(new MockServletContext());
	handler.setLocations(paths);
	handler.setContentNegotiationManager(manager);
	handler.afterPropertiesSet();

	this.request.addHeader("Accept", "application/json,text/plain,*/*");
	this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html");
	handler.handleRequest(this.request, this.response);

	assertEquals("text/html", this.response.getContentType());
}
 
Example 2
@Test
public void resolveViewNameAcceptHeaderSortByQuality() throws Exception {
	request.addHeader("Accept", "text/plain;q=0.5, application/json");

	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(new HeaderContentNegotiationStrategy()));

	ViewResolver htmlViewResolver = mock(ViewResolver.class);
	ViewResolver jsonViewResolver = mock(ViewResolver.class);
	viewResolver.setViewResolvers(Arrays.asList(htmlViewResolver, jsonViewResolver));

	View htmlView = mock(View.class, "text_html");
	View jsonViewMock = mock(View.class, "application_json");

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(htmlViewResolver.resolveViewName(viewName, locale)).willReturn(htmlView);
	given(jsonViewResolver.resolveViewName(viewName, locale)).willReturn(jsonViewMock);
	given(htmlView.getContentType()).willReturn("text/html");
	given(jsonViewMock.getContentType()).willReturn("application/json");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", jsonViewMock, result);
}
 
Example 3
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 6 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
@Nullable
public HandlerMapping resourceHandlerMapping(UrlPathHelper mvcUrlPathHelper,
		PathMatcher mvcPathMatcher,
		ContentNegotiationManager mvcContentNegotiationManager,
		FormattingConversionService mvcConversionService,
		ResourceUrlProvider mvcResourceUrlProvider) {
	Assert.state(this.applicationContext != null, "No ApplicationContext set");
	Assert.state(this.servletContext != null, "No ServletContext set");

	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
			this.servletContext, mvcContentNegotiationManager, mvcUrlPathHelper);
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping == null) {
		return null;
	}
	handlerMapping.setPathMatcher(mvcPathMatcher);
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper);
	handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example 4
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 6 votes vote down vote up
/**
 * A method available to subclasses for adding default
 * {@link HandlerExceptionResolver HandlerExceptionResolvers}.
 * <p>Adds the following exception resolvers:
 * <ul>
 * <li>{@link ExceptionHandlerExceptionResolver} for handling exceptions through
 * {@link org.springframework.web.bind.annotation.ExceptionHandler} methods.
 * <li>{@link ResponseStatusExceptionResolver} for exceptions annotated with
 * {@link org.springframework.web.bind.annotation.ResponseStatus}.
 * <li>{@link DefaultHandlerExceptionResolver} for resolving known Spring exception types
 * </ul>
 */
protected final void addDefaultHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers,
		ContentNegotiationManager mvcContentNegotiationManager) {
	ExceptionHandlerExceptionResolver exceptionHandlerResolver = createExceptionHandlerExceptionResolver();
	exceptionHandlerResolver.setContentNegotiationManager(mvcContentNegotiationManager);
	exceptionHandlerResolver.setMessageConverters(getMessageConverters());
	exceptionHandlerResolver.setCustomArgumentResolvers(getArgumentResolvers());
	exceptionHandlerResolver.setCustomReturnValueHandlers(getReturnValueHandlers());
	if (jackson2Present) {
		exceptionHandlerResolver.setResponseBodyAdvice(
				Collections.singletonList(new JsonViewResponseBodyAdvice()));
	}
	if (this.applicationContext != null) {
		exceptionHandlerResolver.setApplicationContext(this.applicationContext);
	}
	exceptionHandlerResolver.afterPropertiesSet();
	exceptionResolvers.add(exceptionHandlerResolver);

	ResponseStatusExceptionResolver responseStatusResolver = new ResponseStatusExceptionResolver();
	responseStatusResolver.setMessageSource(this.applicationContext);
	exceptionResolvers.add(responseStatusResolver);

	exceptionResolvers.add(new DefaultHandlerExceptionResolver());
}
 
Example 5
@Test
public void resolveViewNameWithAcceptHeader() throws Exception {
	request.addHeader("Accept", "application/vnd.ms-excel");

	Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel"));
	MappingMediaTypeFileExtensionResolver extensionsResolver = new MappingMediaTypeFileExtensionResolver(mapping);
	ContentNegotiationManager manager = new ContentNegotiationManager(new HeaderContentNegotiationStrategy());
	manager.addFileExtensionResolvers(extensionsResolver);
	viewResolver.setContentNegotiationManager(manager);

	ViewResolver viewResolverMock = mock(ViewResolver.class);
	viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));

	View viewMock = mock(View.class, "application_xls");

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
	given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
	given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", viewMock, result);
}
 
Example 6
@Test
public void resolveViewNameWithRequestParameter() throws Exception {
	request.addParameter("format", "xls");

	Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel"));
	ParameterContentNegotiationStrategy paramStrategy = new ParameterContentNegotiationStrategy(mapping);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(paramStrategy));

	ViewResolver viewResolverMock = mock(ViewResolver.class);
	viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
	viewResolver.afterPropertiesSet();

	View viewMock = mock(View.class, "application_xls");

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
	given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
	given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", viewMock, result);
}
 
Example 7
Source Project: java-technology-stack   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testViewResolutionWithContentNegotiation() throws Exception {
	loadBeanDefinitions("mvc-config-view-resolution-content-negotiation.xml");

	ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class);
	assertNotNull(compositeResolver);
	assertEquals(1, compositeResolver.getViewResolvers().size());
	assertEquals(Ordered.HIGHEST_PRECEDENCE, compositeResolver.getOrder());

	List<ViewResolver> resolvers = compositeResolver.getViewResolvers();
	assertEquals(ContentNegotiatingViewResolver.class, resolvers.get(0).getClass());
	ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolvers.get(0);
	assertEquals(6, cnvr.getViewResolvers().size());
	assertEquals(1, cnvr.getDefaultViews().size());
	assertTrue(cnvr.isUseNotAcceptableStatusCode());

	String beanName = "contentNegotiationManager";
	DirectFieldAccessor accessor = new DirectFieldAccessor(cnvr);
	ContentNegotiationManager manager = (ContentNegotiationManager) accessor.getPropertyValue(beanName);
	assertNotNull(manager);
	assertSame(manager, this.appContext.getBean(ContentNegotiationManager.class));
	assertSame(manager, this.appContext.getBean("mvcContentNegotiationManager"));
}
 
Example 8
@Test // SPR-15478
public void wrapConcurrentResult_CollectedValuesListWithResponseEntity() throws Exception {
	List<HttpMessageConverter<?>> converters = Collections.singletonList(new MappingJackson2HttpMessageConverter());
	ResolvableType elementType = ResolvableType.forClass(Bar.class);
	ReactiveTypeHandler.CollectedValuesList result = new ReactiveTypeHandler.CollectedValuesList(elementType);
	result.add(new Bar("foo"));
	result.add(new Bar("bar"));

	ContentNegotiationManager manager = new ContentNegotiationManager();
	this.returnValueHandlers.addHandler(new RequestResponseBodyMethodProcessor(converters, manager));
	ServletInvocableHandlerMethod hm = getHandlerMethod(new ResponseEntityHandler(), "handleFlux");
	hm = hm.wrapConcurrentResult(result);
	hm.invokeAndHandle(this.webRequest, this.mavContainer);

	assertEquals(200, this.response.getStatus());
	assertEquals("[{\"value\":\"foo\"},{\"value\":\"bar\"}]", this.response.getContentAsString());
}
 
Example 9
Source Project: spring-analysis-note   Source File: MvcNamespaceTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testContentNegotiationManager() throws Exception {
	loadBeanDefinitions("mvc-config-content-negotiation-manager.xml");

	RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
	ContentNegotiationManager manager = mapping.getContentNegotiationManager();

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml");
	NativeWebRequest webRequest = new ServletWebRequest(request);
	assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")),
			manager.resolveMediaTypes(webRequest));

	ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class);
	assertNotNull(compositeResolver);
	assertEquals("Actual: " + compositeResolver.getViewResolvers(), 1, compositeResolver.getViewResolvers().size());

	ViewResolver resolver = compositeResolver.getViewResolvers().get(0);
	assertEquals(ContentNegotiatingViewResolver.class, resolver.getClass());
	ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolver;
	assertSame(manager, cnvr.getContentNegotiationManager());
}
 
Example 10
@Test
public void defaultSettings() throws Exception {
	ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();

	this.servletRequest.setRequestURI("/flower.gif");

	assertEquals("Should be able to resolve file extensions by default",
			MediaType.IMAGE_GIF, manager.resolveMediaTypes(this.webRequest).get(0));

	this.servletRequest.setRequestURI("/flower?format=gif");
	this.servletRequest.addParameter("format", "gif");

	assertEquals("Should not resolve request parameters by default",
			ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest));

	this.servletRequest.setRequestURI("/flower");
	this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE);

	assertEquals("Should resolve Accept header by default",
			MediaType.IMAGE_GIF, manager.resolveMediaTypes(this.webRequest).get(0));
}
 
Example 11
Source Project: spring4-understanding   Source File: MvcNamespaceTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testViewResolutionWithContentNegotiation() throws Exception {
	loadBeanDefinitions("mvc-config-view-resolution-content-negotiation.xml", 7);

	ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class);
	assertNotNull(compositeResolver);
	assertEquals(1, compositeResolver.getViewResolvers().size());
	assertEquals(Ordered.HIGHEST_PRECEDENCE, compositeResolver.getOrder());

	List<ViewResolver> resolvers = compositeResolver.getViewResolvers();
	assertEquals(ContentNegotiatingViewResolver.class, resolvers.get(0).getClass());
	ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolvers.get(0);
	assertEquals(7, cnvr.getViewResolvers().size());
	assertEquals(1, cnvr.getDefaultViews().size());
	assertTrue(cnvr.isUseNotAcceptableStatusCode());

	String beanName = "contentNegotiationManager";
	DirectFieldAccessor accessor = new DirectFieldAccessor(cnvr);
	ContentNegotiationManager manager = (ContentNegotiationManager) accessor.getPropertyValue(beanName);
	assertNotNull(manager);
	assertSame(manager, this.appContext.getBean(ContentNegotiationManager.class));
}
 
Example 12
@Test
public void resolveViewNameAcceptHeaderSortByQuality() throws Exception {
	request.addHeader("Accept", "text/plain;q=0.5, application/json");

	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(new HeaderContentNegotiationStrategy()));

	ViewResolver htmlViewResolver = mock(ViewResolver.class);
	ViewResolver jsonViewResolver = mock(ViewResolver.class);
	viewResolver.setViewResolvers(Arrays.asList(htmlViewResolver, jsonViewResolver));

	View htmlView = mock(View.class, "text_html");
	View jsonViewMock = mock(View.class, "application_json");

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(htmlViewResolver.resolveViewName(viewName, locale)).willReturn(htmlView);
	given(jsonViewResolver.resolveViewName(viewName, locale)).willReturn(jsonViewMock);
	given(htmlView.getContentType()).willReturn("text/html");
	given(jsonViewMock.getContentType()).willReturn("application/json");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", jsonViewMock, result);
}
 
Example 13
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 14
Source Project: wallride   Source File: WallRideWebMvcConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public SimpleUrlHandlerMapping mediaUrlHandlerMapping(
		ApplicationContext applicationContext,
		ServletContext servletContext,
		ContentNegotiationManager contentNegotiationManager) {
	MediaHttpRequestHandler handler = new MediaHttpRequestHandler();

	handler.setServletContext(servletContext);
	handler.setApplicationContext(applicationContext);
	handler.setContentNegotiationManager(contentNegotiationManager);

	handler.setWallRideProperties(wallRideProperties);
	handler.setMediaService(mediaService);
	handler.setResourceLoader(resourceLoader);
	handler.setCacheSeconds(86400);

	try {
		handler.afterPropertiesSet();
	} catch (Exception e) {
		throw new BeanInitializationException("Failed to init MediaHttpRequestHandler", e);
	}

	Map<String, HttpRequestHandler> urlMap = new LinkedHashMap<>();
	urlMap.put("/media/{key}", handler);

	SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
	handlerMapping.setOrder(0);
	handlerMapping.setUrlMap(urlMap);
	return handlerMapping;
}
 
Example 15
Source Project: spring-analysis-note   Source File: ProducesRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Same as {@link #ProducesRequestCondition(String[], String[])} but also
 * accepting a {@link ContentNegotiationManager}.
 * @param produces expressions with syntax defined by {@link RequestMapping#produces()}
 * @param headers expressions with syntax defined by {@link RequestMapping#headers()}
 * @param manager used to determine requested media types
 */
public ProducesRequestCondition(String[] produces, @Nullable String[] headers,
		@Nullable ContentNegotiationManager manager) {

	this.expressions = new ArrayList<>(parseExpressions(produces, headers));
	Collections.sort(this.expressions);
	this.contentNegotiationManager = manager != null ? manager : DEFAULT_CONTENT_NEGOTIATION_MANAGER;
}
 
Example 16
@Test
public void setMultipleDefaultContentTypes() throws Exception {
	this.configurer.defaultContentType(MediaType.APPLICATION_JSON, MediaType.ALL);
	ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();

	assertEquals(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.ALL), manager.resolveMediaTypes(this.webRequest));
}
 
Example 17
@Test
public void resolveViewNameFilenameDefaultView() throws Exception {
	request.setRequestURI("/test.json");

	Map<String, MediaType> mapping = Collections.singletonMap("json", MediaType.APPLICATION_JSON);
	PathExtensionContentNegotiationStrategy pathStrategy = new PathExtensionContentNegotiationStrategy(mapping);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(pathStrategy));

	ViewResolver viewResolverMock1 = mock(ViewResolver.class);
	ViewResolver viewResolverMock2 = mock(ViewResolver.class);
	viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));

	View viewMock1 = mock(View.class, "application_xml");
	View viewMock2 = mock(View.class, "text_html");
	View viewMock3 = mock(View.class, "application_json");

	List<View> defaultViews = new ArrayList<>();
	defaultViews.add(viewMock3);
	viewResolver.setDefaultViews(defaultViews);

	viewResolver.afterPropertiesSet();

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
	given(viewResolverMock1.resolveViewName(viewName + ".json", locale)).willReturn(null);
	given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
	given(viewResolverMock2.resolveViewName(viewName + ".json", locale)).willReturn(null);
	given(viewMock1.getContentType()).willReturn("application/xml");
	given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
	given(viewMock3.getContentType()).willReturn("application/json");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", viewMock3, result);
}
 
Example 18
Source Project: problem-spring-web   Source File: AdviceTraitTesting.java    License: MIT License 5 votes vote down vote up
default MockMvc mvc() {
    final ObjectMapper mapper = mapper();

    return MockMvcBuilders
            .standaloneSetup(new ExampleRestController())
            .setContentNegotiationManager(new ContentNegotiationManager(singletonList(
                    new FixedContentNegotiationStrategy(APPLICATION_JSON))))
            .setControllerAdvice(unit())
            .setMessageConverters(
                    new MappingJackson2HttpMessageConverter(mapper),
                    new MappingJackson2XmlHttpMessageConverter())
            .build();
}
 
Example 19
Source Project: java-technology-stack   Source File: ResourceHandlerRegistry.java    License: MIT License 5 votes vote down vote up
/**
 * A variant of
 * {@link #ResourceHandlerRegistry(ApplicationContext, ServletContext, ContentNegotiationManager)}
 * that also accepts the {@link UrlPathHelper} used for mapping requests to static resources.
 * @since 4.3.13
 */
public ResourceHandlerRegistry(ApplicationContext applicationContext, ServletContext servletContext,
		@Nullable ContentNegotiationManager contentNegotiationManager, @Nullable UrlPathHelper pathHelper) {

	Assert.notNull(applicationContext, "ApplicationContext is required");
	this.applicationContext = applicationContext;
	this.servletContext = servletContext;
	this.contentNegotiationManager = contentNegotiationManager;
	this.pathHelper = pathHelper;
}
 
Example 20
Source Project: dhis2-core   Source File: WebConfig.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public ContentNegotiationManager contentNegotiationManager(
    CustomPathExtensionContentNegotiationStrategy customPathExtensionContentNegotiationStrategy,
    ParameterContentNegotiationStrategy parameterContentNegotiationStrategy,
    HeaderContentNegotiationStrategy headerContentNegotiationStrategy,
    FixedContentNegotiationStrategy fixedContentNegotiationStrategy )
{
    return new ContentNegotiationManager( Arrays.asList( customPathExtensionContentNegotiationStrategy,
        parameterContentNegotiationStrategy, headerContentNegotiationStrategy, fixedContentNegotiationStrategy ) );
}
 
Example 21
@Test
public void resolveViewNameFilenameDefaultView() throws Exception {
	request.setRequestURI("/test.json");

	Map<String, MediaType> mapping = Collections.singletonMap("json", MediaType.APPLICATION_JSON);
	PathExtensionContentNegotiationStrategy pathStrategy = new PathExtensionContentNegotiationStrategy(mapping);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(pathStrategy));

	ViewResolver viewResolverMock1 = mock(ViewResolver.class);
	ViewResolver viewResolverMock2 = mock(ViewResolver.class);
	viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));

	View viewMock1 = mock(View.class, "application_xml");
	View viewMock2 = mock(View.class, "text_html");
	View viewMock3 = mock(View.class, "application_json");

	List<View> defaultViews = new ArrayList<View>();
	defaultViews.add(viewMock3);
	viewResolver.setDefaultViews(defaultViews);

	viewResolver.afterPropertiesSet();

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
	given(viewResolverMock1.resolveViewName(viewName + ".json", locale)).willReturn(null);
	given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
	given(viewResolverMock2.resolveViewName(viewName + ".json", locale)).willReturn(null);
	given(viewMock1.getContentType()).willReturn("application/xml");
	given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
	given(viewMock3.getContentType()).willReturn("application/json");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", viewMock3, result);
}
 
Example 22
Source Project: java-technology-stack   Source File: ViewResolverRegistry.java    License: MIT License 5 votes vote down vote up
/**
 * Class constructor with {@link ContentNegotiationManager} and {@link ApplicationContext}.
 * @since 4.3.12
 */
public ViewResolverRegistry(
		ContentNegotiationManager contentNegotiationManager, @Nullable ApplicationContext context) {

	this.contentNegotiationManager = contentNegotiationManager;
	this.applicationContext = context;
}
 
Example 23
@Test
public void favorParameter() throws Exception {
	this.configurer.favorParameter(true);
	this.configurer.parameterName("f");
	this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON));
	ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();

	this.servletRequest.setRequestURI("/flower");
	this.servletRequest.addParameter("f", "json");

	assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0));
}
 
Example 24
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Return a {@link ContentNegotiationManager} instance to use to determine
 * requested {@linkplain MediaType media types} in a given request.
 */
@Bean
public ContentNegotiationManager mvcContentNegotiationManager() {
	if (this.contentNegotiationManager == null) {
		ContentNegotiationConfigurer configurer = new ContentNegotiationConfigurer(this.servletContext);
		configurer.mediaTypes(getDefaultMediaTypes());
		configureContentNegotiation(configurer);
		this.contentNegotiationManager = configurer.buildContentNegotiationManager();
	}
	return this.contentNegotiationManager;
}
 
Example 25
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 26
@Test
public void resolveViewNameWithDefaultContentType() throws Exception {
	request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

	MediaType mediaType = new MediaType("application", "xml");
	FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(mediaType);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));

	ViewResolver viewResolverMock1 = mock(ViewResolver.class, "viewResolver1");
	ViewResolver viewResolverMock2 = mock(ViewResolver.class, "viewResolver2");
	viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
	viewResolver.afterPropertiesSet();

	View viewMock1 = mock(View.class, "application_xml");
	View viewMock2 = mock(View.class, "text_html");

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
	given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
	given(viewMock1.getContentType()).willReturn("application/xml");
	given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", viewMock1, result);
}
 
Example 27
@Test
public void resolveViewNameWithDefaultContentType() throws Exception {
	request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

	MediaType mediaType = new MediaType("application", "xml");
	FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(mediaType);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));

	ViewResolver viewResolverMock1 = mock(ViewResolver.class, "viewResolver1");
	ViewResolver viewResolverMock2 = mock(ViewResolver.class, "viewResolver2");
	viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
	viewResolver.afterPropertiesSet();

	View viewMock1 = mock(View.class, "application_xml");
	View viewMock2 = mock(View.class, "text_html");

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
	given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
	given(viewMock1.getContentType()).willReturn("application/xml");
	given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", viewMock1, result);
}
 
Example 28
/**
 * Constructor with list of converters and ContentNegotiationManager as well
 * as request/response body advice instances.
 */
protected AbstractMessageConverterMethodProcessor(List<HttpMessageConverter<?>> converters,
		ContentNegotiationManager manager, List<Object> requestResponseBodyAdvice) {

	super(converters, requestResponseBodyAdvice);
	this.contentNegotiationManager = (manager != null ? manager : new ContentNegotiationManager());
	this.pathStrategy = initPathStrategy(this.contentNegotiationManager);
	this.safeExtensions.addAll(this.contentNegotiationManager.getAllFileExtensions());
	this.safeExtensions.addAll(WHITELISTED_EXTENSIONS);
}
 
Example 29
@Before
public void setUp() {
	GenericWebApplicationContext appContext = new GenericWebApplicationContext();
	appContext.refresh();

	this.registry = new ResourceHandlerRegistry(appContext, new MockServletContext(),
			new ContentNegotiationManager(), new UrlPathHelper());

	this.registration = this.registry.addResourceHandler("/resources/**");
	this.registration.addResourceLocations("classpath:org/springframework/web/servlet/config/annotation/");
	this.response = new MockHttpServletResponse();
}
 
Example 30
@Test
public void addMediaTypes() throws Exception {
	this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON));
	ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();

	this.servletRequest.setRequestURI("/flower.json");
	assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0));
}