Java Code Examples for org.springframework.http.MediaType#parseMediaType()

The following examples show how to use org.springframework.http.MediaType#parseMediaType() . 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: MessageService.java    From frostmourne with MIT License 6 votes vote down vote up
boolean sendHttpPost(String httpPostEndPoint, AlarmMessage alarmMessage) {
    try {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        Map<String, Object> data = new HashMap<>();
        data.put("recipients", alarmMessage.getRecipients());
        data.put("content", alarmMessage.getContent());
        data.put("title", alarmMessage.getTitle());
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(httpPostEndPoint, request, String.class);
        return responseEntity.getStatusCode() == HttpStatus.OK;
    } catch (Exception ex) {
        LOGGER.error("error when send http post, url: " + httpPostEndPoint, ex);
        return false;
    }
}
 
Example 2
Source File: WxStorageController.java    From mall with MIT License 6 votes vote down vote up
/**
 * 访问存储对象
 *
 * @param key 存储对象key
 * @return
 */
@GetMapping("/fetch/{key:.+}")
public ResponseEntity<Resource> fetch(@PathVariable String key) {
    LitemallStorage litemallStorage = litemallStorageService.findByKey(key);
    if (key == null) {
        return ResponseEntity.notFound().build();
    }
    if (key.contains("../")) {
        return ResponseEntity.badRequest().build();
    }
    String type = litemallStorage.getType();
    MediaType mediaType = MediaType.parseMediaType(type);

    Resource file = storageService.loadAsResource(key);
    if (file == null) {
        return ResponseEntity.notFound().build();
    }
    return ResponseEntity.ok().contentType(mediaType).body(file);
}
 
Example 3
Source File: AbstractMockWebServerTestCase.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private MockResponse multipartRequest(RecordedRequest request) {
	MediaType mediaType = MediaType.parseMediaType(request.getHeader("Content-Type"));
	assertTrue(mediaType.isCompatibleWith(MediaType.MULTIPART_FORM_DATA));
	String boundary = mediaType.getParameter("boundary");
	Buffer body = request.getBody();
	try {
		assertPart(body, "form-data", boundary, "name 1", "text/plain", "value 1");
		assertPart(body, "form-data", boundary, "name 2", "text/plain", "value 2+1");
		assertPart(body, "form-data", boundary, "name 2", "text/plain", "value 2+2");
		assertFilePart(body, "form-data", boundary, "logo", "logo.jpg", "image/jpeg");
	}
	catch (EOFException ex) {
		throw new IllegalStateException(ex);
	}
	return new MockResponse().setResponseCode(200);
}
 
Example 4
Source File: RecipientsReportServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private DownloadRecipientReport getDownloadReportData(ComAdmin admin, String filename, String reportContent) throws UnsupportedEncodingException {
    DownloadRecipientReport recipientReport = new DownloadRecipientReport();
    if (StringUtils.isBlank(reportContent)) {
        reportContent = I18nString.getLocaleString("recipient.reports.notAvailable", admin.getLocale());
        recipientReport.setMediaType(MediaType.TEXT_PLAIN);
        recipientReport.setFilename(FilenameUtils.removeExtension(filename) + RecipientReportUtils.TXT_EXTENSION);
    } else {
        recipientReport.setFilename(RecipientReportUtils.resolveFileName(filename, reportContent));
        MediaType mediaType = MediaType.parseMediaType(mimeTypeService.getMimetypeForFile(filename.toLowerCase()));
        recipientReport.setMediaType(mediaType);
        if (MediaType.TEXT_HTML == mediaType) {
            reportContent = reportContent.replace("\r\n", "\n").replace("\n", "<br />\n");
        }
    }
    
    recipientReport.setContent(reportContent.getBytes("UTF-8"));
    return recipientReport;
}
 
Example 5
Source File: ServletPathExtensionContentNegotiationStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: ServletPathExtensionContentNegotiationStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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} if none found
 * @since 4.3
 */
@Override
public MediaType getMediaTypeForResource(Resource resource) {
	MediaType mediaType = null;
	String mimeType = this.servletContext.getMimeType(resource.getFilename());
	if (StringUtils.hasText(mimeType)) {
		mediaType = MediaType.parseMediaType(mimeType);
	}
	if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) {
		MediaType superMediaType = super.getMediaTypeForResource(resource);
		if (superMediaType != null) {
			mediaType = superMediaType;
		}
	}
	return mediaType;
}
 
Example 7
Source File: ContentResultMatchers.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Assert the ServletResponse content type is compatible with the given
 * content type as defined by {@link MediaType#isCompatibleWith(MediaType)}.
 */
public ResultMatcher contentTypeCompatibleWith(final MediaType contentType) {
	return result -> {
		String actual = result.getResponse().getContentType();
		assertTrue("Content type not set", actual != null);
		if (actual != null) {
			MediaType actualContentType = MediaType.parseMediaType(actual);
			assertTrue("Content type [" + actual + "] is not compatible with [" + contentType + "]",
					actualContentType.isCompatibleWith(contentType));
		}
	};
}
 
Example 8
Source File: ApiClient.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Select the Accept header's value from the given accepts array:
 *     if JSON exists in the given array, use it;
 *     otherwise use all of them (joining into a string)
 *
 * @param accepts The accepts array to select from
 * @return List The list of MediaTypes to use for the Accept header
 */
public List<MediaType> selectHeaderAccept(String[] accepts) {
    if (accepts.length == 0) {
        return null;
    }
    for (String accept : accepts) {
        MediaType mediaType = MediaType.parseMediaType(accept);
        if (isJsonMime(mediaType)) {
            return Collections.singletonList(mediaType);
        }
    }
    return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts));
}
 
Example 9
Source File: UploadViewController.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@GetMapping(value="/**")
public ResponseEntity<InputStreamResource> read(WebRequest webRequest, HttpServletRequest request, HttpServletResponse response){
	String accessablePath = RequestUtils.getServletPath(request);
	if(accessablePath.length()>CONTROLLER_PATH.length()){
		accessablePath = accessablePath.substring(CONTROLLER_PATH.length());
	}else{
		throw new BaseException("error path: " + accessablePath);
	}
	
	String ext = FileUtils.getExtendName(accessablePath).toLowerCase();
	MediaType mediaType = null;
	if(imagePostfix.contains(ext)){
		mediaType = MediaType.parseMediaType("image/"+ext);
	}else{
		mediaType = MediaType.APPLICATION_OCTET_STREAM;
	}
	
	if(webRequest.checkNotModified(fileStorer.getLastModified(accessablePath))){
		return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
								.build();
	}
	
	return ResponseEntity.ok()
						.contentType(mediaType)
						//一起写才起作用
						.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
						.lastModified(new Date().getTime())
						.eTag(accessablePath)
						.body(new InputStreamResource(fileStorer.readFileStream(accessablePath)));
}
 
Example 10
Source File: AbstractMediaTypeExpression.java    From spring-analysis-note with MIT License 5 votes vote down vote up
AbstractMediaTypeExpression(String expression) {
	if (expression.startsWith("!")) {
		this.isNegated = true;
		expression = expression.substring(1);
	}
	else {
		this.isNegated = false;
	}
	this.mediaType = MediaType.parseMediaType(expression);
}
 
Example 11
Source File: ConsumesRequestCondition.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param request the current request
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match.
 */
@Override
public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}
	MediaType contentType;
	try {
		contentType = StringUtils.hasLength(request.getContentType()) ?
				MediaType.parseMediaType(request.getContentType()) :
				MediaType.APPLICATION_OCTET_STREAM;
	}
	catch (InvalidMediaTypeException ex) {
		return null;
	}
	Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<ConsumeMediaTypeExpression>(this.expressions);
	for (Iterator<ConsumeMediaTypeExpression> iterator = result.iterator(); iterator.hasNext();) {
		ConsumeMediaTypeExpression expression = iterator.next();
		if (!expression.match(contentType)) {
			iterator.remove();
		}
	}
	return (result.isEmpty()) ? null : new ConsumesRequestCondition(result);
}
 
Example 12
Source File: RegistryAPI.java    From openvsx with Eclipse Public License 2.0 5 votes vote down vote up
private MediaType getFileType(String fileName) {
    if (fileName.endsWith(".vsix")) {
        return MediaType.APPLICATION_OCTET_STREAM;
    }
    var contentType = URLConnection.guessContentTypeFromName(fileName);
    if (contentType != null) {
        return MediaType.parseMediaType(contentType);
    }
    return MediaType.TEXT_PLAIN;
}
 
Example 13
Source File: MessageService.java    From frostmourne with MIT License 5 votes vote down vote up
boolean sendByDingRobot(String hook, AlarmMessage alarmMessage, List<String> recipients) {
    DingRobotMessage dingRobotMessage = new DingRobotMessage();
    DingAt dingAt = new DingAt();
    dingAt.setAtAll(false);
    dingAt.setAtMobiles(recipients);
    dingRobotMessage.setAt(dingAt);

    DingText dingText = new DingText();
    List<String> atMobiles = recipients.stream().map(m -> "@" + m).collect(Collectors.toList());
    String dingContent = null;
    dingContent = String.format("%s%n%s%n%s", alarmMessage.getTitle(), String.join(" ", atMobiles), alarmMessage.getContent());
    if (dingContent.length() > 18000) {
        dingContent = dingContent.substring(0, 18000);
    }
    dingText.setContent(dingContent);
    dingRobotMessage.setMsgtype("text");
    dingRobotMessage.setText(dingText);

    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    HttpEntity<DingRobotMessage> request = new HttpEntity<>(dingRobotMessage, headers);
    try {
        DingMessageResponse dingMessageResponse = restTemplate.postForObject(hook, request, DingMessageResponse.class);
        return dingMessageResponse != null && dingMessageResponse.getErrcode() != null && dingMessageResponse.getErrcode() == 0;
    } catch (Exception ex) {
        LOGGER.error("error when send ding robot message", ex);
        return false;
    }
}
 
Example 14
Source File: ServletServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) {
	MediaType contentType = headers.getContentType();
	if (contentType == null) {
		String requestContentType = request.getContentType();
		if (StringUtils.hasLength(requestContentType)) {
			contentType = MediaType.parseMediaType(requestContentType);
			headers.setContentType(contentType);
		}
	}
	if (contentType != null && contentType.getCharset() == null) {
		String encoding = request.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 = request.getContentLength();
		if (contentLength != -1) {
			headers.setContentLength(contentLength);
		}
	}
	return headers;
}
 
Example 15
Source File: NotificationMessageHandlerMethodArgumentResolver.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private static MediaType getMediaType(JsonNode content) {
	JsonNode contentTypeNode = content.findPath("MessageAttributes")
			.findPath("contentType");
	if (contentTypeNode.isObject()) {
		String contentType = contentTypeNode.findPath("Value").asText();
		if (StringUtils.hasText(contentType)) {
			return MediaType.parseMediaType(contentType);
		}
	}

	return MediaType.TEXT_PLAIN;
}
 
Example 16
Source File: StorageController.java    From runscore with Apache License 2.0 5 votes vote down vote up
@GetMapping("/fetch/{id:.+}")
public ResponseEntity<Resource> fetch(@PathVariable String id) {
	StorageVO vo = storageService.findById(id);
	if (vo == null) {
		return ResponseEntity.notFound().build();
	}

	String fileType = vo.getFileType();
	MediaType mediaType = MediaType.parseMediaType(fileType);
	Resource file = storageService.loadAsResource(vo.getId());
	if (file == null) {
		return ResponseEntity.notFound().build();
	}
	return ResponseEntity.ok().contentType(mediaType).body(file);
}
 
Example 17
Source File: ResourceHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public static MediaType getMediaType(Resource resource) {
	String filename = resource.getFilename();
	if (filename != null) {
		String mediaType = fileTypeMap.getContentType(filename);
		if (StringUtils.hasText(mediaType)) {
			return MediaType.parseMediaType(mediaType);
		}
	}
	return null;
}
 
Example 18
Source File: HttpPutFormContentFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isFormContentType(HttpServletRequest request) {
	String contentType = request.getContentType();
	if (contentType != null) {
		try {
			MediaType mediaType = MediaType.parseMediaType(contentType);
			return (MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType));
		}
		catch (IllegalArgumentException ex) {
			return false;
		}
	}
	else {
		return false;
	}
}
 
Example 19
Source File: ServletServerHttpRequest.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public HttpHeaders getHeaders() {
	if (this.headers == null) {
		this.headers = new HttpHeaders();

		for (Enumeration<?> headerNames = this.servletRequest.getHeaderNames(); headerNames.hasMoreElements();) {
			String headerName = (String) headerNames.nextElement();
			for (Enumeration<?> headerValues = this.servletRequest.getHeaders(headerName);
					headerValues.hasMoreElements();) {
				String headerValue = (String) headerValues.nextElement();
				this.headers.add(headerName, headerValue);
			}
		}

		// HttpServletRequest exposes some headers as properties: we should include those if not already present
		try {
			MediaType contentType = this.headers.getContentType();
			if (contentType == null) {
				String requestContentType = this.servletRequest.getContentType();
				if (StringUtils.hasLength(requestContentType)) {
					contentType = MediaType.parseMediaType(requestContentType);
					this.headers.setContentType(contentType);
				}
			}
			if (contentType != null && contentType.getCharset() == null) {
				String requestEncoding = this.servletRequest.getCharacterEncoding();
				if (StringUtils.hasLength(requestEncoding)) {
					Charset charSet = Charset.forName(requestEncoding);
					Map<String, String> params = new LinkedCaseInsensitiveMap<String>();
					params.putAll(contentType.getParameters());
					params.put("charset", charSet.toString());
					MediaType newContentType = new MediaType(contentType.getType(), contentType.getSubtype(), params);
					this.headers.setContentType(newContentType);
				}
			}
		}
		catch (InvalidMediaTypeException ex) {
			// Ignore: simply not exposing an invalid content type in HttpHeaders...
		}

		if (this.headers.getContentLength() < 0) {
			int requestContentLength = this.servletRequest.getContentLength();
			if (requestContentLength != -1) {
				this.headers.setContentLength(requestContentLength);
			}
		}
	}

	return this.headers;
}
 
Example 20
Source File: MediaTypeConverter.java    From spring-cloud-dashboard with Apache License 2.0 4 votes vote down vote up
@Override
public MediaType convertFromText(String value, Class<?> targetType, String optionContext) {
	return MediaType.parseMediaType(value);
}