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 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)); }
public class ResultFormatterFactory { private static final Map<MediaType, ResultFormatter> TYPE_TO_FORMATTER_MAP = new HashMap<MediaType, ResultFormatter>() { { put( MediaType.parseMediaType("application/json;charset=UTF-8"), new ResultFormatterJSON()); put( MediaType.parseMediaType("application/ld+json;charset=UTF-8"), new ResultFormatterJSONLD()); put(MediaType.parseMediaType("text/csv;charset=UTF-8"), new ResultFormatterCSV()); put( MediaType.parseMediaType("text/tab-separated-values;charset=UTF-8"), new ResultFormatterTSV()); // a trick to distinguish JSONv2 from JSON put(MediaType.parseMediaType("text/html;charset=UTF-8"), new ResultFormatterJSONv2()); put( MediaType.parseMediaType("text/vnd.graphviz;charset=UTF-8"), new ResultFormatterDOT()); put(MediaType.parseMediaType("image/svg+xml;charset=UTF-8"), new ResultFormatterSVG()); } }; public static final MediaType JSON = MediaType.parseMediaType("application/json;charset=UTF-8"); public ResultFormatter create(MediaType type) { return TYPE_TO_FORMATTER_MAP.get(type == null ? JSON : type); } }
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; }
private Optional<MediaType> getContentType(HttpServletRequest request) { String contentType = request.getContentType(); if (contentType != null) { return Optional.of(MediaType.parseMediaType(contentType)); } return Optional.empty(); }
/** * 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; }
@Test public void testWithConversionService() { ConversionService conversionService = new DefaultConversionService(); assertTrue(conversionService.canConvert(String.class, MediaType.class)); MediaType mediaType = MediaType.parseMediaType("application/xml"); assertEquals(mediaType, conversionService.convert("application/xml", MediaType.class)); }
/** * Generate http request entity from Spring Integration message. * * @param requestMessage * @param method * @return */ private HttpEntity<?> generateRequest(Message<?> requestMessage, HttpMethod method) { HttpHeaders httpHeaders = new HttpHeaders(); headerMapper.fromHeaders(requestMessage.getHeaders(), httpHeaders); Map<String, ?> messageHeaders = requestMessage.getHeaders(); for (Entry<String, ?> header : messageHeaders.entrySet()) { if (!header.getKey().startsWith(CitrusMessageHeaders.PREFIX) && !MessageUtils.isSpringInternalHeader(header.getKey()) && !httpHeaders.containsKey(header.getKey())) { httpHeaders.add(header.getKey(), header.getValue().toString()); } } Object payload = requestMessage.getPayload(); if (httpHeaders.getContentType() == null) { httpHeaders.setContentType( MediaType.parseMediaType( contentType.contains("charset") ? contentType : contentType + ";charset=" + charset)); } if (HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method)) { return new HttpEntity<Object>(payload, httpHeaders); } return new HttpEntity<Object>(httpHeaders); }
public BufferedImageHttpMessageConverter() { String[] readerMediaTypes = ImageIO.getReaderMIMETypes(); for (String mediaType : readerMediaTypes) { if (StringUtils.hasText(mediaType)) { this.readableMediaTypes.add(MediaType.parseMediaType(mediaType)); } } String[] writerMediaTypes = ImageIO.getWriterMIMETypes(); for (String mediaType : writerMediaTypes) { if (StringUtils.hasText(mediaType)) { this.defaultContentType = MediaType.parseMediaType(mediaType); break; } } }
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 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); }
@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 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()); }
/** * Set the mapping from file extensions to media types. * * <p>When this mapping is not set or when an extension is not present, this view resolver will * fall back to using a {@link FileTypeMap} when the Java Action Framework is available. */ public void setMediaTypes(Map<String, String> mediaTypes) { Assert.notNull(mediaTypes, "'mediaTypes' must not be null"); for (Map.Entry<String, String> entry : mediaTypes.entrySet()) { String extension = entry.getKey().toLowerCase(Locale.ENGLISH); MediaType mediaType = MediaType.parseMediaType(entry.getValue()); this.mediaTypes.put(extension, mediaType); } }
boolean isContentTypeMatch(HttpServletRequest request, MockData mock) { String mockContentType = mock.getRequestMediaType(); if (mockContentType != null) { MediaType requestContentType = getContentType(request).orElse(MediaType.ALL); return MediaType.parseMediaType(mockContentType).includes(requestContentType); } return true; }
@Test public void resultsNonauthorizedExceptionForNoLoginRequiredLocaly() throws Exception { mvc.perform(get("/results-nonauthorized").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect( content() .contentTypeCompatibleWith( MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE))); }
@Test public void invokePlugin() throws Exception { this.mockMvc .perform( get("/scala-plugin?parameter=test") .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()) .andExpect(content().string("scala-plugin with test")); }
/** * 发送post请求返回字符串 * * @param url post-URL: * @param postData post的数据 * @return 返回post请求响应的数据 */ public static String postUrl(String url, String postData) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); HttpEntity<String> formEntity = new HttpEntity<String>(postData, headers); return restTemplate.postForObject(url, formEntity, String.class); }
@Test public void resultsClientOnly() throws Exception { mvc.perform(get("/results").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect( content() .contentTypeCompatibleWith( MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE))); }
/** 处理JSR311 Validation异常. */ @ExceptionHandler(value = {ConstraintViolationException.class}) public final ResponseEntity<?> handleException( ConstraintViolationException ex, WebRequest request) { Map<String, String> errors = BeanValidators.extractPropertyAndMessage(ex.getConstraintViolations()); String body = jsonMapper.toJson(errors); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8)); return handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request); }
/** * Extends the base class {@link PathExtensionContentNegotiationStrategy#getMediaTypeForResource} * with the ability to also look up through the ServletContext. * * @param resource the resource to look up * @return the MediaType for the extension or {@code null}. * @since 4.3 */ public MediaType getMediaTypeForResource(Resource resource) { MediaType mediaType = super.getMediaTypeForResource(resource); if (mediaType == null) { String mimeType = this.servletContext.getMimeType(resource.getFilename()); if (StringUtils.hasText(mimeType)) { mediaType = MediaType.parseMediaType(mimeType); } } if (MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { mediaType = null; } return mediaType; }
@Override public Object extractData(ClientHttpResponse response) throws IOException { if (MediaType.IMAGE_JPEG.includes(response.getHeaders().getContentType()) || MediaType.parseMediaType(AUDIO_CONTENT_TYPE) .includes(response.getHeaders().getContentType())) { return new MediaMultipartFile(response); } else if (stringHttpMessageConverter.canRead( String.class, response.getHeaders().getContentType())) { return MessageMapper.fromJson( stringHttpMessageConverter.read(String.class, (HttpInputMessage) response), MpResponse.class); } return null; }
@Override public ProfilePhoto readUserProfilePhoto(long userId) { InputStream fileInputSteam = null; try { User user = findById(userId); fileInputSteam = new FileInputStream(fileForPhoto(userId)); byte[] data = IOUtils.toByteArray(fileInputSteam); return new ProfilePhoto( userId, data, MediaType.parseMediaType(user.getProfilePhotoMediaType())); } catch (Exception e) { throw new UserProfilePhotoReadException(userId, e); } finally { IOUtils.closeQuietly(fileInputSteam); } }
@RequestMapping(value = IMAGES + "/{fileName}.{fileType}") public void getImage( @PathVariable String fileName, @PathVariable String fileType, @RequestParam(required = false) String version, HttpServletResponse response) throws IOException { FileImageFinder.FileInfo file = imageFinder.getFile(fileName + "." + fileType, version); response.setContentType(MediaType.parseMediaType("image/" + fileType).toString()); response.setContentLength(file.bytes.length); response.setHeader("Last-Modified", file.modifyTime); response.setHeader("Cache-Control", "public, max-age=3153600"); response.getOutputStream().write(file.bytes); }
/** * Resolve file extension via {@link ServletContext#getMimeType(String)} and also delegate to base * class for a potential JAF lookup. */ @Override protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension) throws HttpMediaTypeNotAcceptableException { MediaType mediaType = null; if (this.servletContext != null) { String mimeType = this.servletContext.getMimeType("file." + extension); if (StringUtils.hasText(mimeType)) { mediaType = MediaType.parseMediaType(mimeType); } } if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { MediaType superMediaType = super.handleNoMatch(webRequest, extension); if (superMediaType != null) { mediaType = superMediaType; } } return mediaType; }
{ put( MediaType.parseMediaType("application/json;charset=UTF-8"), new ResultFormatterJSON()); put( MediaType.parseMediaType("application/ld+json;charset=UTF-8"), new ResultFormatterJSONLD()); put(MediaType.parseMediaType("text/csv;charset=UTF-8"), new ResultFormatterCSV()); put( MediaType.parseMediaType("text/tab-separated-values;charset=UTF-8"), new ResultFormatterTSV()); // a trick to distinguish JSONv2 from JSON put(MediaType.parseMediaType("text/html;charset=UTF-8"), new ResultFormatterJSONv2()); put( MediaType.parseMediaType("text/vnd.graphviz;charset=UTF-8"), new ResultFormatterDOT()); put(MediaType.parseMediaType("image/svg+xml;charset=UTF-8"), new ResultFormatterSVG()); }
@RequestMapping(value = "/image/{id}", method = RequestMethod.GET) public ResponseEntity<byte[]> getImage( @PathVariable long id, HttpServletRequest request, HttpServletResponse response) { checkRequiredEntity(appFileService, id); AppFile appFile = appFileService.get(id); if (!ContentType.IMAGE.equals(MimeType.getForFilename(appFile.getName()).getContentType())) { throw new RuntimeException( String.format("Attempted to pull file which wasn't an image: %s", id)); } response.setHeader( "Cache-Control", String.format("public, max-age=%s", 31556900 /*Seconds in a year*/)); response.setDateHeader("Last-Modified", appFile.getLastUpdate().getTime()); Calendar calendar = Calendar.getInstance(); calendar.setTime(appFile.getLastUpdate()); calendar.add(Calendar.YEAR, 1); response.setHeader("Expires", httpDateFormat.format(calendar.getTime())); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(appFile.getType())); StorageService storageService = storageServiceFactory.getStorageService(appFile.getStorageType()); long requestIfModifiedSince = request.getDateHeader("If-Modified-Since"); if (requestIfModifiedSince >= appFile.getLastUpdate().getTime()) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return null; } if (storageService instanceof RemoteStorageService) { byte[] bytes = readImageFromUrl(appFile, (RemoteStorageService) storageService); return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED); } else { byte[] bytes = readImageFromFile(appFile); return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED); } }
@RequestMapping( value = "/saveAsZip/filename/{uuid}/{filename}", method = RequestMethod.GET, produces = "application/zip") public ResponseEntity<InputStreamResource> saveAsZip( @PathVariable String uuid, @PathVariable String filename) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add("Content-Disposition", "attachment; filename=" + filename + ".zip"); headers.add("Set-Cookie", "fileDownload=true; path=/"); byte[] data = createZip(uuid); routeRepository.clearRoutes(uuid); return ResponseEntity.ok() .headers(headers) .contentLength(data.length) .contentType(MediaType.parseMediaType("application/zip")) .body(new InputStreamResource(new ByteArrayInputStream(data))); }
/** * Generates the Http response message from given Spring Integration message. * * @param responseMessage message received from the message handler * @return an HTTP entity as response */ private ResponseEntity<String> generateResponse(Message<?> responseMessage) { if (responseMessage == null) { return new ResponseEntity<String>(HttpStatus.OK); } HttpHeaders httpHeaders = new HttpHeaders(); headerMapper.fromHeaders(responseMessage.getHeaders(), httpHeaders); Map<String, ?> messageHeaders = responseMessage.getHeaders(); for (Entry<String, ?> header : messageHeaders.entrySet()) { if (!header.getKey().startsWith(CitrusMessageHeaders.PREFIX) && !MessageUtils.isSpringInternalHeader(header.getKey()) && !httpHeaders.containsKey(header.getKey())) { httpHeaders.add(header.getKey(), header.getValue().toString()); } } if (httpHeaders.getContentType() == null) { httpHeaders.setContentType( MediaType.parseMediaType( contentType.contains("charset") ? contentType : contentType + ";charset=" + charset)); } HttpStatus status = HttpStatus.OK; if (responseMessage.getHeaders().containsKey(CitrusHttpMessageHeaders.HTTP_STATUS_CODE)) { status = HttpStatus.valueOf( Integer.valueOf( responseMessage .getHeaders() .get(CitrusHttpMessageHeaders.HTTP_STATUS_CODE) .toString())); } responseCache = new ResponseEntity<String>(responseMessage.getPayload().toString(), httpHeaders, status); return responseCache; }
@Override protected HttpHeaders initHeaders() { HttpHeaders headers = new HttpHeaders(); for (Enumeration<?> names = getServletRequest().getHeaderNames(); names.hasMoreElements(); ) { String name = (String) names.nextElement(); for (Enumeration<?> values = getServletRequest().getHeaders(name); values.hasMoreElements(); ) { headers.add(name, (String) values.nextElement()); } } MediaType contentType = headers.getContentType(); if (contentType == null) { String requestContentType = getServletRequest().getContentType(); if (StringUtils.hasLength(requestContentType)) { contentType = MediaType.parseMediaType(requestContentType); headers.setContentType(contentType); } } if (contentType != null && contentType.getCharset() == null) { String encoding = getServletRequest().getCharacterEncoding(); if (StringUtils.hasLength(encoding)) { Charset charset = Charset.forName(encoding); Map<String, String> params = new LinkedCaseInsensitiveMap<>(); params.putAll(contentType.getParameters()); params.put("charset", charset.toString()); headers.setContentType( new MediaType(contentType.getType(), contentType.getSubtype(), params)); } } if (headers.getContentLength() == -1) { int contentLength = getServletRequest().getContentLength(); if (contentLength != -1) { headers.setContentLength(contentLength); } } return headers; }