protected Map<String, MediaType> getDefaultMediaTypes() { Map<String, MediaType> map = new HashMap<>(4); if (romePresent) { map.put("atom", MediaType.APPLICATION_ATOM_XML); map.put("rss", MediaType.APPLICATION_RSS_XML); } if (jaxb2Present || jackson2XmlPresent) { map.put("xml", MediaType.APPLICATION_XML); } if (jackson2Present || gsonPresent || jsonbPresent) { map.put("json", MediaType.APPLICATION_JSON); } if (jackson2SmilePresent) { map.put("smile", MediaType.valueOf("application/x-jackson-smile")); } if (jackson2CborPresent) { map.put("cbor", MediaType.valueOf("application/cbor")); } return map; }
/** * Add a mapping from a key, extracted from a path extension or a query * parameter, to a MediaType. This is required in order for the parameter * strategy to work. Any extensions explicitly registered here are also * whitelisted for the purpose of Reflected File Download attack detection * (see Spring Framework reference documentation for more details on RFD * attack protection). * <p>The path extension strategy will also try to use * {@link ServletContext#getMimeType} and * {@link org.springframework.http.MediaTypeFactory} to resolve path extensions. * @param mediaTypes media type mappings * @see #addMediaType(String, MediaType) * @see #addMediaTypes(Map) */ public void setMediaTypes(Properties mediaTypes) { if (!CollectionUtils.isEmpty(mediaTypes)) { mediaTypes.forEach((key, value) -> { String extension = ((String) key).toLowerCase(Locale.ENGLISH); MediaType mediaType = MediaType.valueOf((String) value); this.mediaTypes.put(extension, mediaType); }); } }
private static HttpHeaders getDefaultTokenRequestHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); final MediaType contentType = MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"); headers.setContentType(contentType); return headers; } }
protected Map<String, MediaType> getDefaultMediaTypes() { Map<String, MediaType> map = new HashMap<>(4); if (romePresent) { map.put("atom", MediaType.APPLICATION_ATOM_XML); map.put("rss", MediaType.APPLICATION_RSS_XML); } if (jaxb2Present || jackson2XmlPresent) { map.put("xml", MediaType.APPLICATION_XML); } if (jackson2Present || gsonPresent || jsonbPresent) { map.put("json", MediaType.APPLICATION_JSON); } if (jackson2SmilePresent) { map.put("smile", MediaType.valueOf("application/x-jackson-smile")); } if (jackson2CborPresent) { map.put("cbor", MediaType.valueOf("application/cbor")); } return map; }
/** * Add a mapping from a key, extracted from a path extension or a query * parameter, to a MediaType. This is required in order for the parameter * strategy to work. Any extensions explicitly registered here are also * whitelisted for the purpose of Reflected File Download attack detection * (see Spring Framework reference documentation for more details on RFD * attack protection). * <p>The path extension strategy will also try to use * {@link ServletContext#getMimeType} and * {@link org.springframework.http.MediaTypeFactory} to resolve path extensions. * @param mediaTypes media type mappings * @see #addMediaType(String, MediaType) * @see #addMediaTypes(Map) */ public void setMediaTypes(Properties mediaTypes) { if (!CollectionUtils.isEmpty(mediaTypes)) { mediaTypes.forEach((key, value) -> { String extension = ((String) key).toLowerCase(Locale.ENGLISH); MediaType mediaType = MediaType.valueOf((String) value); this.mediaTypes.put(extension, mediaType); }); } }
@SuppressWarnings("unchecked") @Test public void convertWhenGrantRequestValidThenConverts() { RequestEntity<?> requestEntity = this.converter.convert(this.clientCredentialsGrantRequest); ClientRegistration clientRegistration = this.clientCredentialsGrantRequest.getClientRegistration(); assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST); assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo( clientRegistration.getProviderDetails().getTokenUri()); HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8); assertThat(headers.getContentType()).isEqualTo( MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody(); assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE)).isEqualTo( AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()); assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("read write"); } }
@SuppressWarnings("unchecked") @Test public void convertWhenGrantRequestValidThenConverts() { RequestEntity<?> requestEntity = this.converter.convert(this.authorizationCodeGrantRequest); ClientRegistration clientRegistration = this.authorizationCodeGrantRequest.getClientRegistration(); assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST); assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo( clientRegistration.getProviderDetails().getTokenUri()); HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8); assertThat(headers.getContentType()).isEqualTo( MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody(); assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE)).isEqualTo( AuthorizationGrantType.AUTHORIZATION_CODE.getValue()); assertThat(formParameters.getFirst(OAuth2ParameterNames.CODE)).isEqualTo("code-1234"); assertThat(formParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI)).isEqualTo( clientRegistration.getRedirectUriTemplate()); } }
body::get); requestBodySpec.contentType(MediaType.valueOf(request.getEntity().getContentType().getValue())); requestBodySpec.body(Mono.fromSupplier(body::get), String.class); } else {
@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()); }
@SuppressWarnings("unchecked") @Test public void convertWhenAuthenticationMethodFormThenPostRequest() { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() .userInfoAuthenticationMethod(AuthenticationMethod.FORM) .build(); OAuth2UserRequest userRequest = new OAuth2UserRequest( clientRegistration, this.createAccessToken()); RequestEntity<?> requestEntity = this.converter.convert(userRequest); assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST); assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo( clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()); HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON); assertThat(headers.getContentType()).isEqualTo( MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody(); assertThat(formParameters.getFirst(OAuth2ParameterNames.ACCESS_TOKEN)).isEqualTo( userRequest.getAccessToken().getTokenValue()); }
@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); }
@Test public void contentNegotiation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.json"); NativeWebRequest webRequest = new ServletWebRequest(request); RequestMappingHandlerMapping mapping = this.config.requestMappingHandlerMapping(); ContentNegotiationManager manager = mapping.getContentNegotiationManager(); assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest)); request.setRequestURI("/foo.xml"); assertEquals(Collections.singletonList(APPLICATION_XML), manager.resolveMediaTypes(webRequest)); request.setRequestURI("/foo.rss"); assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")), manager.resolveMediaTypes(webRequest)); request.setRequestURI("/foo.atom"); assertEquals(Collections.singletonList(APPLICATION_ATOM_XML), manager.resolveMediaTypes(webRequest)); request.setRequestURI("/foo"); request.setParameter("f", "json"); assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest)); request.setRequestURI("/resources/foo.gif"); SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) this.config.resourceHandlerMapping(); handlerMapping.setApplicationContext(this.context); HandlerExecutionChain chain = handlerMapping.getHandler(request); assertNotNull(chain); ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) chain.getHandler(); assertNotNull(handler); assertSame(manager, handler.getContentNegotiationManager()); }
@Test // SPR-9841 public void handleReturnValueMediaTypeSuffix() throws Exception { String body = "Foo"; MediaType accepted = MediaType.APPLICATION_XHTML_XML; List<MediaType> supported = Collections.singletonList(MediaType.valueOf("application/*+xml")); servletRequest.addHeader("Accept", accepted); given(stringMessageConverter.canWrite(String.class, null)).willReturn(true); given(stringMessageConverter.getSupportedMediaTypes()).willReturn(supported); given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(true); processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); verify(stringMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); }
@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); }
@Test public void testContentType() throws Exception { this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) .andExpect(content().contentType(MediaType.valueOf("text/plain;charset=ISO-8859-1"))) .andExpect(content().contentType("text/plain;charset=ISO-8859-1")) .andExpect(content().contentTypeCompatibleWith("text/plain")) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)); this.mockMvc.perform(get("/handleUtf8")) .andExpect(content().contentType(MediaType.valueOf("text/plain;charset=UTF-8"))) .andExpect(content().contentType("text/plain;charset=UTF-8")) .andExpect(content().contentTypeCompatibleWith("text/plain")) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)); }
/** * Returns the {@link LinkDiscoverer} suitable for the given media type. * * @param mediaType * @return */ public LinkDiscoverer getLinkDiscovererFor(String mediaType) { return getLinkDiscovererFor(MediaType.valueOf(mediaType)); } }
@Test public void canWrite() { assertFalse(this.converter.canWrite(Math.class, null)); assertFalse(this.converter.canWrite(Resource.class, null)); assertTrue(this.converter.canWrite(Locale.class, null)); assertTrue(this.converter.canWrite(Double.class, null)); assertFalse(this.converter.canWrite(BigInteger.class, MediaType.TEXT_HTML)); assertFalse(this.converter.canWrite(BigInteger.class, MediaType.TEXT_XML)); assertFalse(this.converter.canWrite(BigInteger.class, MediaType.APPLICATION_XML)); assertTrue(this.converter.canWrite(BigInteger.class, MediaType.valueOf("text/*"))); }
private HttpHeaders createBasicAuthenticationHeader(BaremetalVlanStruct struct) { String plainCreds = String.format("%s:%s", struct.getSwitchUsername(), struct.getSwitchPassword()); byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + base64Creds); headers.setAccept(Arrays.asList(MediaType.ALL)); headers.setContentType(MediaType.valueOf("application/vnd.yang.data+xml")); return headers; }
@Test public void testContentTypeInboundHeader() throws Exception { HeaderMapper<HttpHeaders> mapper = DefaultHttpHeaderMapper.inboundMapper(); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE.toLowerCase(), "text/plain"); Map<String, ?> result = mapper.toHeaders(headers); assertEquals(MediaType.valueOf("text/plain"), result.get(MessageHeaders.CONTENT_TYPE)); }