org.springframework.web.accept.ContentNegotiationManager Java Examples

The following examples show how to use org.springframework.web.accept.ContentNegotiationManager. 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: ResourceHttpRequestHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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
Source File: ContentNegotiatingViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 File: WebMvcConfigurationSupport.java    From spring-analysis-note with 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 File: ContentNegotiatingViewResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #5
Source File: WebMvcConfigurationSupport.java    From spring-analysis-note with 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 #6
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #7
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #8
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 #9
Source File: MvcNamespaceTests.java    From spring4-understanding with 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 #10
Source File: MvcNamespaceTests.java    From java-technology-stack with 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 #11
Source File: ServletInvocableHandlerMethodTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #12
Source File: ContentNegotiationConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #13
Source File: MvcNamespaceTests.java    From spring-analysis-note with 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 #14
Source File: WebMvcConfigurationSupport.java    From spring-analysis-note with 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 #15
Source File: ContentNegotiatingViewResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #16
Source File: AbstractMessageConverterMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Constructor with list of converters and ContentNegotiationManager as well
 * as request/response body advice instances.
 */
protected AbstractMessageConverterMethodProcessor(List<HttpMessageConverter<?>> converters,
		@Nullable ContentNegotiationManager manager, @Nullable 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 #17
Source File: AdviceTraitTesting.java    From problem-spring-web with 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 #18
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static PathExtensionContentNegotiationStrategy initPathStrategy(ContentNegotiationManager manager) {
	for (ContentNegotiationStrategy strategy : manager.getStrategies()) {
		if (strategy instanceof PathExtensionContentNegotiationStrategy) {
			return (PathExtensionContentNegotiationStrategy) strategy;
		}
	}
	return new PathExtensionContentNegotiationStrategy();
}
 
Example #19
Source File: ContentNegotiationConfigurerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #20
Source File: AdminServerWebConfiguration.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Bean
public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping adminHandlerMapping(
		ContentNegotiationManager contentNegotiationManager) {
	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping mapping = new de.codecentric.boot.admin.server.web.servlet.AdminControllerHandlerMapping(
			this.adminServerProperties.getContextPath());
	mapping.setOrder(0);
	mapping.setContentNegotiationManager(contentNegotiationManager);
	return mapping;
}
 
Example #21
Source File: WebMvcConfigurationSupport.java    From spring-analysis-note with 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 #22
Source File: ResourceHandlerRegistryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #23
Source File: ContentNegotiationConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setDefaultContentTypeStrategy() throws Exception {
	this.configurer.defaultContentTypeStrategy(new FixedContentNegotiationStrategy(MediaType.APPLICATION_JSON));
	ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();

	assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0));
}
 
Example #24
Source File: AbstractMessageConverterMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #25
Source File: ContentNegotiatingViewResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: ContentNegotiationConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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));
}
 
Example #27
Source File: ContentNegotiationConfigurerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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));
}
 
Example #28
Source File: ContentNegotiationConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setDefaultContentType() throws Exception {
	this.configurer.defaultContentType(MediaType.APPLICATION_JSON);
	ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager();

	assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0));
}
 
Example #29
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #30
Source File: ContentNegotiationConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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));
}