@Override protected void writeInternal(String t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { MediaType contentType = outputMessage.getHeaders().getContentType(); Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET; FileCopyUtils.copy(t, new OutputStreamWriter(outputMessage.getBody(), charset)); }
@Test public void headers() throws URISyntaxException { MediaType accept = MediaType.TEXT_PLAIN; Charset charset = Charset.forName("UTF-8"); long ifModifiedSince = 12345L; String ifNoneMatch = "\"foo\""; long contentLength = 67890; MediaType contentType = MediaType.TEXT_PLAIN; RequestEntity<Void> responseEntity = RequestEntity.post(new URI("http://example.com")) .accept(accept) .acceptCharset(charset) .ifModifiedSince(ifModifiedSince) .ifNoneMatch(ifNoneMatch) .contentLength(contentLength) .contentType(contentType) .build(); assertNotNull(responseEntity); assertEquals(HttpMethod.POST, responseEntity.getMethod()); assertEquals(new URI("http://example.com"), responseEntity.getUrl()); HttpHeaders responseHeaders = responseEntity.getHeaders(); assertEquals("text/plain", responseHeaders.getFirst("Accept")); assertEquals("utf-8", responseHeaders.getFirst("Accept-Charset")); assertEquals("Thu, 01 Jan 1970 00:00:12 GMT", responseHeaders.getFirst("If-Modified-Since")); assertEquals(ifNoneMatch, responseHeaders.getFirst("If-None-Match")); assertEquals(String.valueOf(contentLength), responseHeaders.getFirst("Content-Length")); assertEquals(contentType.toString(), responseHeaders.getFirst("Content-Type")); assertNull(responseEntity.getBody()); }
@Override public void write(JSONEntity entity, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // First write the entity to a JSON string try { HttpHeaders headers = outputMessage.getHeaders(); if (headers.getContentType() == null) { if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) { contentType = MediaType.APPLICATION_JSON; } if (contentType != null) { headers.setContentType(contentType); } } String jsonString = EntityFactory.createJSONStringForEntity(entity); long length = JSONEntityHttpMessageConverter.writeToStream( jsonString, outputMessage.getBody(), contentType.getCharSet()); if (headers.getContentLength() == -1) { headers.setContentLength(length); } } catch (JSONObjectAdapterException e) { throw new HttpMessageNotWritableException(e.getMessage()); } }
@Override protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { MediaType contentType = inputMessage.getHeaders().getContentType(); Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET; return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset)); }
@Test public void putTest() throws RestClientException, URISyntaxException { String url = dirFrontEnd + "/empresa/nifPrueba"; String acceptHeaderValue = "application/json"; HttpHeaders requestHeaders = new HttpHeaders(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.valueOf(acceptHeaderValue)); requestHeaders.setAccept(mediaTypes); requestHeaders.setContentType(MediaType.valueOf(acceptHeaderValue)); HttpMethod put = HttpMethod.PUT; String body = "{\"nombre\":\"nombrePruebaModificado\"}"; HttpEntity<String> entity = new HttpEntity<String>(body, requestHeaders); ResponseEntity<String> response = restTemplate.exchange(url, put, entity, String.class); assertTrue(response.getStatusCode().equals(HttpStatus.NO_CONTENT)); String nombreEmpresa = (String) jdbcTemplate.queryForObject( "SELECT NOMBRE FROM EMPRESA WHERE NIF= ?", new Object[] {"nifPrueba"}, String.class); assertTrue(nombreEmpresa.equals("nombrePruebaModificado")); }
@Test public void postTest() throws RestClientException, URISyntaxException { String url = dirFrontEnd + "/empresa/"; String acceptHeaderValue = "application/json"; HttpHeaders requestHeaders = new HttpHeaders(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.valueOf(acceptHeaderValue)); requestHeaders.setAccept(mediaTypes); requestHeaders.setContentType(MediaType.valueOf(acceptHeaderValue)); HttpMethod post = HttpMethod.POST; String body = "{\"nif\":\"nifPrueba\",\"nombre\":\"nombrePrueba\",\"direccionFiscal\":\"DirPrueba\",\"fechaInicioActividades\":\"2014-01-10\",\"version\":\"0\"}"; HttpEntity<String> entity = new HttpEntity<String>(body, requestHeaders); ResponseEntity<String> response = restTemplate.exchange(url, post, entity, String.class); assertTrue(response.getStatusCode().equals(HttpStatus.CREATED)); String nombreEmpresa = (String) jdbcTemplate.queryForObject( "SELECT NOMBRE FROM EMPRESA WHERE NIF= ?", new Object[] {"nifPrueba"}, String.class); assertTrue(nombreEmpresa.equals("nombrePrueba")); }
@Override public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ImageInputStream imageInputStream = null; ImageReader imageReader = null; try { imageInputStream = createImageInputStream(inputMessage.getBody()); MediaType contentType = inputMessage.getHeaders().getContentType(); Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString()); if (imageReaders.hasNext()) { imageReader = imageReaders.next(); ImageReadParam irp = imageReader.getDefaultReadParam(); process(irp); imageReader.setInput(imageInputStream, true); return imageReader.read(0, irp); } else { throw new HttpMessageNotReadableException( "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]"); } } finally { if (imageReader != null) { imageReader.dispose(); } if (imageInputStream != null) { try { imageInputStream.close(); } catch (IOException ex) { // ignore } } } }
@SuppressWarnings("unchecked") public void doWithRequest(ClientHttpRequest request) throws IOException { if (responseType != null) { List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); for (HttpMessageConverter<?> messageConverter : getMessageConverters()) { if (messageConverter.canRead(responseType, null)) { List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes(); for (MediaType supportedMediaType : supportedMediaTypes) { if (supportedMediaType.getCharSet() != null) { supportedMediaType = new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype()); } allSupportedMediaTypes.add(supportedMediaType); } } } if (!allSupportedMediaTypes.isEmpty()) { MediaType.sortBySpecificity(allSupportedMediaTypes); if (logger.isDebugEnabled()) { logger.debug("Setting request Accept header to " + allSupportedMediaTypes); } request.getHeaders().setAccept(allSupportedMediaTypes); } } }
private View getBestView(List<View> candidateViews, List<MediaType> requestedMediaTypes) { for (View candidateView : candidateViews) { if (candidateView instanceof SmartView) { SmartView smartView = (SmartView) candidateView; if (smartView.isRedirectView()) { if (logger.isDebugEnabled()) { logger.debug("Returning redirect view [" + candidateView + "]"); } return candidateView; } } } for (MediaType mediaType : requestedMediaTypes) { for (View candidateView : candidateViews) { if (StringUtils.hasText(candidateView.getContentType())) { MediaType candidateContentType = MediaType.parseMediaType(candidateView.getContentType()); if (mediaType.includes(candidateContentType)) { if (logger.isDebugEnabled()) { logger.debug( "Returning [" + candidateView + "] based on requested media type '" + mediaType + "'"); } return candidateView; } } } } return null; }
public class PersonControllerTest { private static final MediaType FORM_URL = MediaType.parseMediaType("application/x-www-form-urlencoded"); private static final MediaType JSON_UTF8 = MediaType.parseMediaType("application/json;charset=UTF-8"); private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(new PersonController()).build(); } @Test public void testPostAndGet() throws Exception { mockMvc .perform( post("/") .contentType(FORM_URL) .param("forename", "Buzz") .param("surname", "Aldrin") .param("age", "85")) .andDo(MockMvcResultHandlers.print()) .andExpect(status().isCreated()); mockMvc .perform(get("/").contentType(JSON_UTF8)) .andDo(MockMvcResultHandlers.print()) .andExpect(jsonPath("$.forename", is("Buzz"))) .andExpect(jsonPath("$.surname", is("Aldrin"))) .andExpect(jsonPath("$.age", is(85))); } }
@Test @SuppressWarnings("unchecked") public void Can_create_a_user_for_a_specific_content_type() { final MediaType contentTypeOne = APPLICATION_FORM_URLENCODED; final MediaType contentTypeTwo = APPLICATION_JSON; final UserFactory<HttpServletRequest> userFactoryOne = mock(UserFactory.class); final UserFactory<HttpServletRequest> userFactoryTwo = mock(UserFactory.class); final Map<MediaType, UserFactory<HttpServletRequest>> factories = new HashMap<MediaType, UserFactory<HttpServletRequest>>() { { put(contentTypeOne, userFactoryOne); put(contentTypeTwo, userFactoryTwo); } }; final HttpServletRequest request = mock(HttpServletRequest.class); final User expected = mock(PersistedUser.class); // Given given(request.getContentType()).willReturn(contentTypeTwo.toString()); given(userFactoryTwo.create(request)).willReturn(expected); // When final User actual = new ContentTypeUserFactory(factories).create(request); // Then assertThat(actual, equalTo(expected)); }
/** * Indicate whether this {@code MediaType} is compatible with the given media type. * * <p>For instance, {@code text/*} is compatible with {@code text/plain}, {@code text/html}, and * vice versa. In effect, this method is similar to {@link #includes(MediaType)}, except that it * <b>is</b> symmetric. * * @param other the reference media type with which to compare * @return <code>true</code> if this media type is compatible with the given media type; <code> * false</code> otherwise */ public boolean isCompatibleWith(MediaType other) { if (other == null) { return false; } if (isWildcardType() || other.isWildcardType()) { return true; } else if (this.type.equals(other.type)) { if (this.subtype.equals(other.subtype) || this.isWildcardSubtype() || other.isWildcardSubtype()) { return true; } // application/*+xml is compatible with application/soap+xml, and vice-versa int thisPlusIdx = this.subtype.indexOf('+'); int otherPlusIdx = other.subtype.indexOf('+'); if (thisPlusIdx != -1 && otherPlusIdx != -1) { String thisSubtypeNoSuffix = this.subtype.substring(0, thisPlusIdx); String otherSubtypeNoSuffix = other.subtype.substring(0, otherPlusIdx); String thisSubtypeSuffix = this.subtype.substring(thisPlusIdx + 1); String otherSubtypeSuffix = other.subtype.substring(otherPlusIdx + 1); if (thisSubtypeSuffix.equals(otherSubtypeSuffix) && (WILDCARD_TYPE.equals(thisSubtypeNoSuffix) || WILDCARD_TYPE.equals(otherSubtypeNoSuffix))) { return true; } } } return false; }
private String determineEncoding(String contentTypeHeader, String defaultEncoding) { if (!StringUtils.hasText(contentTypeHeader)) { return defaultEncoding; } MediaType contentType = MediaType.parseMediaType(contentTypeHeader); Charset charset = contentType.getCharSet(); return (charset != null ? charset.name() : defaultEncoding); }
@Test public void parseQuotedCharset() { String s = "application/xml;charset=\"utf-8\""; MediaType mediaType = MediaType.parseMediaType(s); assertEquals("Invalid type", "application", mediaType.getType()); assertEquals("Invalid subtype", "xml", mediaType.getSubtype()); assertEquals("Invalid charset", Charset.forName("UTF-8"), mediaType.getCharSet()); }
@Test public void parseCharset() throws Exception { String s = "text/html; charset=iso-8859-1"; MediaType mediaType = MediaType.parseMediaType(s); assertEquals("Invalid type", "text", mediaType.getType()); assertEquals("Invalid subtype", "html", mediaType.getSubtype()); assertEquals("Invalid charset", Charset.forName("ISO-8859-1"), mediaType.getCharSet()); }
@Test public void parseURLConnectionMediaType() throws Exception { String s = "*; q=.2"; MediaType mediaType = MediaType.parseMediaType(s); assertEquals("Invalid type", "*", mediaType.getType()); assertEquals("Invalid subtype", "*", mediaType.getSubtype()); assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D); }
public static boolean isJSONType(MediaType type) { if (type == null) return false; if (type.getType() == null) return false; if (type.getSubtype() == null) return false; if (!"application".equals(type.getType().toLowerCase())) return false; if (!"json".equals(type.getSubtype().toLowerCase())) return false; return true; }
private int indexOfEqualMediaType(MediaType mediaType) { for (int i = 0; i < getExpressionsToCompare().size(); i++) { MediaType currentMediaType = getExpressionsToCompare().get(i).getMediaType(); if (mediaType.getType().equalsIgnoreCase(currentMediaType.getType()) && mediaType.getSubtype().equalsIgnoreCase(currentMediaType.getSubtype())) { return i; } } return -1; }
/** * Return a string representation of the given list of {@code MediaType} objects. * * <p>This method can be used to for an {@code Accept} or {@code Content-Type} header. * * @param mediaTypes the string to parse * @return the list of media types * @throws IllegalArgumentException if the String cannot be parsed */ public static String toString(Collection<MediaType> mediaTypes) { StringBuilder builder = new StringBuilder(); for (Iterator<MediaType> iterator = mediaTypes.iterator(); iterator.hasNext(); ) { MediaType mediaType = iterator.next(); mediaType.appendTo(builder); if (iterator.hasNext()) { builder.append(", "); } } return builder.toString(); }
/** * Returns {@code true} if the given media type includes any of the {@linkplain * #setSupportedMediaTypes(List) supported media types}. * * @param mediaType the media type to write, can be {@code null} if not specified. Typically the * value of an {@code Accept} header. * @return {@code true} if the supported media types are compatible with the media type, or if the * media type is {@code null} */ protected boolean canWrite(MediaType mediaType) { if (mediaType == null || MediaType.ALL.equals(mediaType)) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { if (supportedMediaType.isCompatibleWith(mediaType)) { return true; } } return false; }
/** * Returns true if any of the {@linkplain #setSupportedMediaTypes(List) supported} media types * {@link MediaType#includes(MediaType) include} the given media type. * * @param mediaType the media type to read, can be {@code null} if not specified. Typically the * value of a {@code Content-Type} header. * @return {@code true} if the supported media types include the media type, or if the media type * is {@code null} */ protected boolean canRead(MediaType mediaType) { if (mediaType == null) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { if (supportedMediaType.includes(mediaType)) { return true; } } return false; }
/** * Determine the JSON encoding to use for the given content type. * * @param contentType the media type as requested by the caller * @return the JSON encoding to use (never {@code null}) */ protected JsonEncoding getJsonEncoding(MediaType contentType) { if (contentType != null && contentType.getCharset() != null) { Charset charset = contentType.getCharset(); for (JsonEncoding encoding : JsonEncoding.values()) { if (charset.name().equals(encoding.getJavaName())) { return encoding; } } } return JsonEncoding.UTF8; }
@Test public void parseMediaTypes() throws Exception { String s = "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"; List<MediaType> mediaTypes = MediaType.parseMediaTypes(s); assertNotNull("No media types returned", mediaTypes); assertEquals("Invalid amount of media types", 4, mediaTypes.size()); mediaTypes = MediaType.parseMediaTypes(null); assertNotNull("No media types returned", mediaTypes); assertEquals("Invalid amount of media types", 0, mediaTypes.size()); }
@Test(expected = HttpMediaTypeNotSupportedException.class) public void resolveArgumentNotReadable() throws Exception { MediaType contentType = MediaType.TEXT_PLAIN; servletRequest.addHeader("Content-Type", contentType.toString()); expect(messageConverter.canRead(String.class, contentType)).andReturn(false); replay(messageConverter); processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); fail("Expected exception"); }
@Override protected Long getContentLength(String s, MediaType contentType) { if (contentType != null && contentType.getCharSet() != null) { Charset charset = contentType.getCharSet(); try { return (long) s.getBytes(charset.name()).length; } catch (UnsupportedEncodingException ex) { throw new InternalError(ex.getMessage()); } } else { return null; } }
@Override protected View createView(String viewName, Locale locale) throws Exception { View view = super.createView(viewName, locale); if (viewName.startsWith(FORWARD_URL_PREFIX) || viewName.startsWith(REDIRECT_URL_PREFIX)) { if (view instanceof AbstractView) { MediaType requestedMediaType = getRequestedMediaType(); if (requestedMediaType != null) { ((AbstractView) view).setContentType(requestedMediaType.toString()); } } } return view; }
public boolean canWrite(Class<?> clazz, MediaType mediaType) { if (!Map.class.isAssignableFrom(clazz)) { return false; } if (mediaType == null || MediaType.ALL.equals(mediaType)) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { if (supportedMediaType.isCompatibleWith(mediaType)) { return true; } } return false; }
@Test public void compareToConsistentWithEquals() { MediaType m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1"); MediaType m2 = MediaType.parseMediaType("text/html; charset=iso-8859-1; q=0.7"); assertEquals("Media types not equal", m1, m2); assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2)); assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1)); m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1"); m2 = MediaType.parseMediaType("text/html; Q=0.7; charset=iso-8859-1"); assertEquals("Media types not equal", m1, m2); assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2)); assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1)); }
@Test(expected = HttpMediaTypeNotAcceptableException.class) public void handleReturnValueNotAcceptableProduces() throws Exception { MediaType accepted = MediaType.TEXT_PLAIN; servletRequest.addHeader("Accept", accepted.toString()); expect(messageConverter.canWrite(String.class, null)).andReturn(true); expect(messageConverter.getSupportedMediaTypes()) .andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); replay(messageConverter); processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest); fail("Expected exception"); }
/** * Determines the {@link MediaType} for the given filename. * * <p>The default implementation will check the {@linkplain #setMediaTypes(Map) media types} * property first for a defined mapping. If not present, and if the Java Activation Framework can * be found on the classpath, it will call {@link FileTypeMap#getContentType(String)} * * <p>This method can be overridden to provide a different algorithm. * * @param filename the current request file name (i.e. {@code hotels.html}) * @return the media type, if any */ protected MediaType getMediaTypeFromFilename(String filename) { String extension = StringUtils.getFilenameExtension(filename); if (!StringUtils.hasText(extension)) { return null; } extension = extension.toLowerCase(Locale.ENGLISH); MediaType mediaType = this.mediaTypes.get(extension); if (mediaType == null) { String mimeType = getServletContext().getMimeType(filename); if (StringUtils.hasText(mimeType)) { mediaType = MediaType.parseMediaType(mimeType); } if (this.useJaf && (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType))) { MediaType jafMediaType = ActivationMediaTypeFactory.getMediaType(filename); if (jafMediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(jafMediaType)) { mediaType = jafMediaType; } } if (mediaType != null) { this.mediaTypes.putIfAbsent(extension, mediaType); } } return mediaType; }