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

The following examples show how to use org.springframework.http.MediaType#valueOf() . 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: MediaTypeTest.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void parseTest() {
    MediaType mediaType = MediaType.valueOf("image/gif");

    assertNotNull(mediaType);
    assertThat(mediaType, equalTo(MediaType.IMAGE_GIF));
}
 
Example 2
Source File: MediaTypeTest.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void includesTest() {
    MediaType mediaType = MediaType.valueOf("image/*");
    boolean isInclude = mediaType.includes(MediaType.IMAGE_GIF);
    assertTrue(isInclude);

    isInclude = mediaType.includes(MediaType.IMAGE_JPEG);
    assertTrue(isInclude);

    isInclude = mediaType.includes(MediaType.IMAGE_PNG);
    assertTrue(isInclude);

    isInclude = mediaType.includes(MediaType.TEXT_HTML);
    assertFalse(isInclude);
}
 
Example 3
Source File: WireMockRestServiceServer.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private MediaType contentType(ResponseDefinition response) {
	String value = null;
	if (response.getHeaders() != null) {
		HttpHeader header = response.getHeaders().getHeader("Content-Type");
		if (header != null && header.isPresent()) {
			value = header.firstValue();
		}
	}
	return value == null ? MediaType.TEXT_PLAIN : MediaType.valueOf(value);
}
 
Example 4
Source File: RequestUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static MediaType getAcceptAsMediaType(HttpServletRequest request){
	String accept = request.getHeader("Accept");
	try {
		MediaType mtype = MediaType.valueOf(accept);
		return mtype;
	} catch (Exception e) {
		logger.error("parse [{}] as MediaType error: " + e.getMessage(), accept);
		return null;
	}
}
 
Example 5
Source File: MediaTypeTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
	MediaType mtype = MediaType.valueOf("application/json");
	MediaType jsonUtf8 = MediaType.valueOf("application/json;charset=UTF-8");
	Assert.assertTrue(jsonUtf8.isCompatibleWith(mtype));
	Assert.assertTrue(mtype.isCompatibleWith(jsonUtf8));
}
 
Example 6
Source File: ExtSpringEncoder.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected MediaType getRequestContentType(RequestTemplate request){
	Collection<String> contentTypes = request.headers().get("Content-Type");

	MediaType requestContentType = null;
	if (contentTypes != null && !contentTypes.isEmpty()) {
		String type = contentTypes.iterator().next();
		requestContentType = MediaType.valueOf(type);
	}
	return requestContentType;
}
 
Example 7
Source File: CommonConfiguration.java    From jetlinks-community with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T convert(Class<T> aClass, Object o) {
    return (T) MediaType.valueOf(String.valueOf(o));
}
 
Example 8
Source File: WebClientPlugin.java    From soul with Apache License 2.0 4 votes vote down vote up
private MediaType buildMediaType(final ServerWebExchange exchange) {
    return MediaType.valueOf(Optional.ofNullable(exchange
            .getRequest()
            .getHeaders().getFirst(HttpHeaders.CONTENT_TYPE))
            .orElse(MediaType.APPLICATION_JSON_VALUE));
}
 
Example 9
Source File: SpringEncoder.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
@Override
public void encode(Object requestBody, Type bodyType, RequestTemplate request)
		throws EncodeException {
	// template.body(conversionService.convert(object, String.class));
	if (requestBody != null) {
		Collection<String> contentTypes = request.headers()
				.get(HttpEncoding.CONTENT_TYPE);

		MediaType requestContentType = null;
		if (contentTypes != null && !contentTypes.isEmpty()) {
			String type = contentTypes.iterator().next();
			requestContentType = MediaType.valueOf(type);
		}

		if (Objects.equals(requestContentType, MediaType.MULTIPART_FORM_DATA)) {
			this.springFormEncoder.encode(requestBody, bodyType, request);
			return;
		}
		else {
			if (bodyType == MultipartFile.class) {
				log.warn(
						"For MultipartFile to be handled correctly, the 'consumes' parameter of @RequestMapping "
								+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
			}
		}

		for (HttpMessageConverter messageConverter : this.messageConverters
				.getObject().getConverters()) {
			FeignOutputMessage outputMessage;
			try {
				if (messageConverter instanceof GenericHttpMessageConverter) {
					outputMessage = checkAndWrite(requestBody, bodyType,
							requestContentType,
							(GenericHttpMessageConverter) messageConverter, request);
				}
				else {
					outputMessage = checkAndWrite(requestBody, requestContentType,
							messageConverter, request);
				}
			}
			catch (IOException | HttpMessageConversionException ex) {
				throw new EncodeException("Error converting request body", ex);
			}
			if (outputMessage != null) {
				// clear headers
				request.headers(null);
				// converters can modify headers, so update the request
				// with the modified headers
				request.headers(getHeaders(outputMessage.getHeaders()));

				// do not use charset for binary data and protobuf
				Charset charset;
				if (messageConverter instanceof ByteArrayHttpMessageConverter) {
					charset = null;
				}
				else if (messageConverter instanceof ProtobufHttpMessageConverter
						&& ProtobufHttpMessageConverter.PROTOBUF.isCompatibleWith(
								outputMessage.getHeaders().getContentType())) {
					charset = null;
				}
				else {
					charset = StandardCharsets.UTF_8;
				}
				request.body(Request.Body.encoded(
						outputMessage.getOutputStream().toByteArray(), charset));
				return;
			}
		}
		String message = "Could not write request: no suitable HttpMessageConverter "
				+ "found for request type [" + requestBody.getClass().getName() + "]";
		if (requestContentType != null) {
			message += " and content type [" + requestContentType + "]";
		}
		throw new EncodeException(message);
	}
}
 
Example 10
Source File: BladeMediaType.java    From blade-tool with GNU Lesser General Public License v3.0 4 votes vote down vote up
public BladeMediaType(String version) {
	this.version = version;
	this.mediaType = MediaType.valueOf(String.format(MEDIA_TYPE_TEMP, appName, version));
}
 
Example 11
Source File: ContractResultHandler.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
@Override
protected MediaType getContentType(MvcResult result) {
	return MediaType.valueOf(result.getRequest().getContentType());
}
 
Example 12
Source File: CatnapMessageConverter.java    From catnap with Apache License 2.0 4 votes vote down vote up
public CatnapMessageConverter(final T view) {
    super(MediaType.valueOf(view.getContentType()));
    this.view = view;
}
 
Example 13
Source File: CatnapMessageConverter.java    From catnap with Apache License 2.0 4 votes vote down vote up
public CatnapMessageConverter(final T view) {
    super(MediaType.valueOf(view.getContentType()));
    this.view = view;
}
 
Example 14
Source File: ConfigurableContentNegotiationManagerWebMvcConfigurer.java    From spring-webmvc-support with GNU General Public License v3.0 3 votes vote down vote up
@Override
public void setAsText(String text) {

    MediaType mediaType = MediaType.valueOf(text);

    setValue(mediaType);

}
 
Example 15
Source File: ContentNegotiationManagerFactoryBean.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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 JAF (if present) to resolve path
 * extensions. To change this behavior see the {@link #useJaf} property.
 * @param mediaTypes media type mappings
 * @see #addMediaType(String, MediaType)
 * @see #addMediaTypes(Map)
 */
public void setMediaTypes(Properties mediaTypes) {
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		for (Entry<Object, Object> entry : mediaTypes.entrySet()) {
			String extension = ((String)entry.getKey()).toLowerCase(Locale.ENGLISH);
			MediaType mediaType = MediaType.valueOf((String) entry.getValue());
			this.mediaTypes.put(extension, mediaType);
		}
	}
}
 
Example 16
Source File: ContentNegotiationManagerFactoryBean.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * 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 JAF (if present) to resolve path
 * extensions. To change this behavior see the {@link #useJaf} property.
 * @param mediaTypes media type mappings
 * @see #addMediaType(String, MediaType)
 * @see #addMediaTypes(Map)
 */
public void setMediaTypes(Properties mediaTypes) {
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		for (Entry<Object, Object> entry : mediaTypes.entrySet()) {
			String extension = ((String)entry.getKey()).toLowerCase(Locale.ENGLISH);
			MediaType mediaType = MediaType.valueOf((String) entry.getValue());
			this.mediaTypes.put(extension, mediaType);
		}
	}
}