org.springframework.web.accept.HeaderContentNegotiationStrategy Java Examples

The following examples show how to use org.springframework.web.accept.HeaderContentNegotiationStrategy. 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: 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 #2
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note 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 #3
Source File: ProducesRequestConditionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // gh-22853
public void matchAndCompare() {
	ContentNegotiationManager manager = new ContentNegotiationManager(
			new HeaderContentNegotiationStrategy(),
			new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

	ProducesRequestCondition none = new ProducesRequestCondition(new String[0], null, manager);
	ProducesRequestCondition html = new ProducesRequestCondition(new String[] {"text/html"}, null, manager);

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addHeader("Accept", "*/*");

	ProducesRequestCondition noneMatch = none.getMatchingCondition(request);
	ProducesRequestCondition htmlMatch = html.getMatchingCondition(request);

	assertEquals(1, noneMatch.compareTo(htmlMatch, request));
}
 
Example #4
Source File: ContentNegotiatingViewResolverTests.java    From java-technology-stack 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 #5
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 #6
Source File: SecurityConfig.java    From pizzeria with MIT License 6 votes vote down vote up
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
    ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy();

    MediaTypeRequestMatcher jsonMediaTypeRequestMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy, MediaType.APPLICATION_JSON);
    jsonMediaTypeRequestMatcher.setUseEquals(true);

    LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler = new LinkedHashMap<>();
    matcherToHandler.put(jsonMediaTypeRequestMatcher, new HttpStatusReturningLogoutSuccessHandler());

    DelegatingLogoutSuccessHandler delegatingLogoutSuccessHandler = new DelegatingLogoutSuccessHandler(matcherToHandler);

    SimpleUrlLogoutSuccessHandler simpleUrlLogoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
    simpleUrlLogoutSuccessHandler.setUseReferer(true);
    simpleUrlLogoutSuccessHandler.setDefaultTargetUrl("/");

    delegatingLogoutSuccessHandler.setDefaultLogoutSuccessHandler(simpleUrlLogoutSuccessHandler);

    return delegatingLogoutSuccessHandler;
}
 
Example #7
Source File: ContentNegotiatingViewResolverTests.java    From spring4-understanding with Apache License 2.0 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 #8
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 #9
Source File: SpringletsSecurityWebAuthenticationEntryPoint.java    From springlets with Apache License 2.0 6 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
    AuthenticationException authException) throws IOException, ServletException {

  ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy();
  MediaTypeRequestMatcher matcher =
      new MediaTypeRequestMatcher(negotiationStrategy, MediaType.TEXT_HTML);
  matcher.setUseEquals(false);

  if (matcher.matches(request)) {
    DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    redirectStrategy.setContextRelative(false);
    redirectStrategy.sendRedirect(request, response, LOGIN_FORM_URL);
  } else {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
  }
}
 
Example #10
Source File: SpringletsSecurityWebAccessDeniedHandlerImpl.java    From springlets with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
    AccessDeniedException accessDeniedException) throws IOException, ServletException {

  ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy();
  MediaTypeRequestMatcher matcher =
      new MediaTypeRequestMatcher(negotiationStrategy, MediaType.TEXT_HTML);
  matcher.setUseEquals(false);

  if (matcher.matches(request)) {
    DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    redirectStrategy.setContextRelative(false);
    redirectStrategy.sendRedirect(request, response, "/errores/403");
  } else {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);

  }

}
 
Example #11
Source File: ViewResolutionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testContentNegotiation() throws Exception {

	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(Person.class);

	List<View> viewList = new ArrayList<View>();
	viewList.add(new MappingJackson2JsonView());
	viewList.add(new MarshallingView(marshaller));

	ContentNegotiationManager manager = new ContentNegotiationManager(
			new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

	ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
	cnViewResolver.setDefaultViews(viewList);
	cnViewResolver.setContentNegotiationManager(manager);
	cnViewResolver.afterPropertiesSet();

	MockMvc mockMvc =
		standaloneSetup(new PersonController())
			.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
			.build();

	mockMvc.perform(get("/person/Corea"))
		.andExpect(status().isOk())
		.andExpect(model().size(1))
		.andExpect(model().attributeExists("person"))
		.andExpect(forwardedUrl("person/show"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_JSON))
		.andExpect(jsonPath("$.person.name").value("Corea"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_XML))
		.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
 
Example #12
Source File: WebConfig.java    From dhis2-core with 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 #13
Source File: ViewResolutionTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void testContentNegotiation() throws Exception {
	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(Person.class);

	List<View> viewList = new ArrayList<>();
	viewList.add(new MappingJackson2JsonView());
	viewList.add(new MarshallingView(marshaller));

	ContentNegotiationManager manager = new ContentNegotiationManager(
			new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

	ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
	cnViewResolver.setDefaultViews(viewList);
	cnViewResolver.setContentNegotiationManager(manager);
	cnViewResolver.afterPropertiesSet();

	MockMvc mockMvc =
		standaloneSetup(new PersonController())
			.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
			.build();

	mockMvc.perform(get("/person/Corea"))
		.andExpect(status().isOk())
		.andExpect(model().size(1))
		.andExpect(model().attributeExists("person"))
		.andExpect(forwardedUrl("person/show"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_JSON))
		.andExpect(jsonPath("$.person.name").value("Corea"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_XML))
		.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
 
Example #14
Source File: ViewResolutionTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void testContentNegotiation() throws Exception {
	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(Person.class);

	List<View> viewList = new ArrayList<>();
	viewList.add(new MappingJackson2JsonView());
	viewList.add(new MarshallingView(marshaller));

	ContentNegotiationManager manager = new ContentNegotiationManager(
			new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));

	ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
	cnViewResolver.setDefaultViews(viewList);
	cnViewResolver.setContentNegotiationManager(manager);
	cnViewResolver.afterPropertiesSet();

	MockMvc mockMvc =
		standaloneSetup(new PersonController())
			.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
			.build();

	mockMvc.perform(get("/person/Corea"))
		.andExpect(status().isOk())
		.andExpect(model().size(1))
		.andExpect(model().attributeExists("person"))
		.andExpect(forwardedUrl("person/show"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_JSON))
		.andExpect(jsonPath("$.person.name").value("Corea"));

	mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
		.andExpect(status().isOk())
		.andExpect(content().contentType(MediaType.APPLICATION_XML))
		.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
 
Example #15
Source File: WebConfig.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Bean
public HeaderContentNegotiationStrategy headerContentNegotiationStrategy()
{
    return new HeaderContentNegotiationStrategy();
}
 
Example #16
Source File: ContentNegotiationManagerConfigurationDisabledTest.java    From spring-boot-web-support with GNU General Public License v3.0 3 votes vote down vote up
@Test
public void testContentNegotiationManagerConfigurationOnDisabled() {

    Assert.assertFalse(BeanUtils.isBeanPresent(applicationContext, ContentNegotiationManagerConfiguration.class));

    ContentNegotiationManager contentNegotiationManager =
            contentNegotiatingViewResolver.getContentNegotiationManager();

    List<ContentNegotiationStrategy> strategies = contentNegotiationManager.getStrategies();

    Assert.assertEquals(1, strategies.size());
    Assert.assertTrue(contains(HeaderContentNegotiationStrategy.class, strategies));

}