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

The following examples show how to use org.springframework.http.MediaType#equals() . 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: FormHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
	if (!MultiValueMap.class.isAssignableFrom(clazz)) {
		return false;
	}
	if (mediaType == null) {
		return true;
	}
	for (MediaType supportedMediaType : getSupportedMediaTypes()) {
		// We can't read multipart....
		if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) {
			return true;
		}
	}
	return false;
}
 
Example 2
Source File: FormHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
	if (!MultiValueMap.class.isAssignableFrom(clazz)) {
		return false;
	}
	if (mediaType == null) {
		return true;
	}
	for (MediaType supportedMediaType : getSupportedMediaTypes()) {
		// We can't read multipart....
		if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) {
			return true;
		}
	}
	return false;
}
 
Example 3
Source File: FormHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
	if (!MultiValueMap.class.isAssignableFrom(clazz)) {
		return false;
	}
	if (mediaType == null) {
		return true;
	}
	for (MediaType supportedMediaType : getSupportedMediaTypes()) {
		// We can't read multipart....
		if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) {
			return true;
		}
	}
	return false;
}
 
Example 4
Source File: FormHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
	if (!MultiValueMap.class.isAssignableFrom(clazz)) {
		return false;
	}
	if (mediaType == null) {
		return true;
	}
	for (MediaType supportedMediaType : getSupportedMediaTypes()) {
		// We can't read multipart....
		if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) {
			return true;
		}
	}
	return false;
}
 
Example 5
Source File: FormHttpMessageConverter.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
	if (!MultiValueMap.class.isAssignableFrom(clazz)) {
		return false;
	}
	if (mediaType == null) {
		return true;
	}
	for (MediaType supportedMediaType : getSupportedMediaTypes()) {
		// We can't read multipart....
		if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) {
			return true;
		}
	}
	return false;
}
 
Example 6
Source File: ResourceHttpMessageWriter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static MediaType getResourceMediaType(
		@Nullable MediaType mediaType, Resource resource, Map<String, Object> hints) {

	if (mediaType != null && mediaType.isConcrete() && !mediaType.equals(MediaType.APPLICATION_OCTET_STREAM)) {
		return mediaType;
	}
	mediaType = MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM);
	if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
		logger.debug(Hints.getLogPrefix(hints) + "Resource associated with '" + mediaType + "'");
	}
	return mediaType;
}
 
Example 7
Source File: ResourceHttpMessageWriter.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static MediaType getResourceMediaType(
		@Nullable MediaType mediaType, Resource resource, Map<String, Object> hints) {

	if (mediaType != null && mediaType.isConcrete() && !mediaType.equals(MediaType.APPLICATION_OCTET_STREAM)) {
		return mediaType;
	}
	mediaType = MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM);
	if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
		logger.debug(Hints.getLogPrefix(hints) + "Resource associated with '" + mediaType + "'");
	}
	return mediaType;
}
 
Example 8
Source File: MetricsResponse.java    From timely with Apache License 2.0 5 votes vote down vote up
public TextWebSocketFrame toWebSocketResponse(String acceptHeader) throws Exception {
    MediaType negotiatedType = MediaType.TEXT_HTML;
    if (null != acceptHeader) {
        List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
        MediaType.sortBySpecificityAndQuality(requestedTypes);
        LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
        for (MediaType t : requestedTypes) {
            if (t.includes(MediaType.TEXT_HTML)) {
                negotiatedType = MediaType.TEXT_HTML;
                LOG.trace("{} allows HTML", t.toString());
                break;
            }
            if (t.includes(MediaType.APPLICATION_JSON)) {
                negotiatedType = MediaType.APPLICATION_JSON;
                LOG.trace("{} allows JSON", t.toString());
                break;
            }
        }
    }
    String result = null;
    if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
        result = this.generateJson(JsonUtil.getObjectMapper());
    } else {
        result = this.generateHtml().toString();
    }
    return new TextWebSocketFrame(result);
}
 
Example 9
Source File: MetricsResponse.java    From timely with Apache License 2.0 5 votes vote down vote up
public FullHttpResponse toHttpResponse(String acceptHeader) throws Exception {
    MediaType negotiatedType = MediaType.TEXT_HTML;
    if (null != acceptHeader) {
        List<MediaType> requestedTypes = MediaType.parseMediaTypes(acceptHeader);
        MediaType.sortBySpecificityAndQuality(requestedTypes);
        LOG.trace("Acceptable response types: {}", MediaType.toString(requestedTypes));
        for (MediaType t : requestedTypes) {
            if (t.includes(MediaType.TEXT_HTML)) {
                negotiatedType = MediaType.TEXT_HTML;
                LOG.trace("{} allows HTML", t.toString());
                break;
            }
            if (t.includes(MediaType.APPLICATION_JSON)) {
                negotiatedType = MediaType.APPLICATION_JSON;
                LOG.trace("{} allows JSON", t.toString());
                break;
            }
        }
    }
    byte[] buf = null;
    Object responseType = Constants.HTML_TYPE;
    if (negotiatedType.equals(MediaType.APPLICATION_JSON)) {
        buf = this.generateJson(JsonUtil.getObjectMapper()).getBytes(StandardCharsets.UTF_8);
        responseType = Constants.JSON_TYPE;
    } else {
        buf = this.generateHtml().toString().getBytes(StandardCharsets.UTF_8);
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, responseType);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example 10
Source File: EncoderHttpMessageWriter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private static boolean useFallback(@Nullable MediaType main, @Nullable MediaType fallback) {
	return (main == null || !main.isConcrete() ||
			main.equals(MediaType.APPLICATION_OCTET_STREAM) && fallback != null);
}
 
Example 11
Source File: EncoderHttpMessageWriter.java    From java-technology-stack with MIT License 4 votes vote down vote up
private static boolean useFallback(@Nullable MediaType main, @Nullable MediaType fallback) {
	return (main == null || !main.isConcrete() ||
			main.equals(MediaType.APPLICATION_OCTET_STREAM) && fallback != null);
}
 
Example 12
Source File: HttpMessageConverterResolver.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
/**
 * Resolve the most match {@link HttpMessageConverter} from {@link RequestMetadata}.
 * @param requestMetadata {@link RequestMetadata}
 * @param restMethodMetadata {@link RestMethodMetadata}
 * @return instance of {@link HttpMessageConverterHolder}
 */
public HttpMessageConverterHolder resolve(RequestMetadata requestMetadata,
		RestMethodMetadata restMethodMetadata) {

	HttpMessageConverterHolder httpMessageConverterHolder = null;

	Class<?> returnValueClass = resolveReturnValueClass(restMethodMetadata);

	/**
	 * @see AbstractMessageConverterMethodProcessor#writeWithMessageConverters(T,
	 * MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse)
	 */
	List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(requestMetadata);
	List<MediaType> producibleMediaTypes = getProducibleMediaTypes(restMethodMetadata,
			returnValueClass);

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
	for (MediaType requestedType : requestedMediaTypes) {
		for (MediaType producibleType : producibleMediaTypes) {
			if (requestedType.isCompatibleWith(producibleType)) {
				compatibleMediaTypes
						.add(getMostSpecificMediaType(requestedType, producibleType));
			}
		}
	}

	if (compatibleMediaTypes.isEmpty()) {
		return httpMessageConverterHolder;
	}

	List<MediaType> mediaTypes = new ArrayList<>(compatibleMediaTypes);

	MediaType.sortBySpecificityAndQuality(mediaTypes);

	MediaType selectedMediaType = null;
	for (MediaType mediaType : mediaTypes) {
		if (mediaType.isConcrete()) {
			selectedMediaType = mediaType;
			break;
		}
		else if (mediaType.equals(MediaType.ALL)
				|| mediaType.equals(MEDIA_TYPE_APPLICATION)) {
			selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selectedMediaType != null) {
		selectedMediaType = selectedMediaType.removeQualityValue();
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
				httpMessageConverterHolder = new HttpMessageConverterHolder(
						selectedMediaType, messageConverter);
				break;
			}
		}
	}

	return httpMessageConverterHolder;
}
 
Example 13
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the given return type to the given output message.
 * @param returnValue the value to write to the output message
 * @param returnType the type of the value
 * @param inputMessage the input messages. Used to inspect the {@code Accept} header.
 * @param outputMessage the output message to write to
 * @throws IOException thrown in case of I/O errors
 * @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated by {@code Accept} header on
 * the request cannot be met by the message converters
 */
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType,
		ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	Class<?> returnValueClass = getReturnValueType(returnValue, returnType);
	Type returnValueType = getGenericType(returnType);
	HttpServletRequest servletRequest = inputMessage.getServletRequest();
	List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);
	List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass, returnValueType);

	if (returnValue != null && producibleMediaTypes.isEmpty()) {
		throw new IllegalArgumentException("No converter found for return value of type: " + returnValueClass);
	}

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
	for (MediaType requestedType : requestedMediaTypes) {
		for (MediaType producibleType : producibleMediaTypes) {
			if (requestedType.isCompatibleWith(producibleType)) {
				compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));
			}
		}
	}
	if (compatibleMediaTypes.isEmpty()) {
		if (returnValue != null) {
			throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
		}
		return;
	}

	List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
	MediaType.sortBySpecificityAndQuality(mediaTypes);

	MediaType selectedMediaType = null;
	for (MediaType mediaType : mediaTypes) {
		if (mediaType.isConcrete()) {
			selectedMediaType = mediaType;
			break;
		}
		else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
			selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selectedMediaType != null) {
		selectedMediaType = selectedMediaType.removeQualityValue();
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				if (((GenericHttpMessageConverter<T>) messageConverter).canWrite(returnValueType,
						returnValueClass, selectedMediaType)) {
					returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
							(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
							inputMessage, outputMessage);
					if (returnValue != null) {
						addContentDispositionHeader(inputMessage, outputMessage);
						((GenericHttpMessageConverter<T>) messageConverter).write(returnValue,
								returnValueType, selectedMediaType, outputMessage);
						if (logger.isDebugEnabled()) {
							logger.debug("Written [" + returnValue + "] as \"" +
									selectedMediaType + "\" using [" + messageConverter + "]");
						}
					}
					return;
				}
			}
			else if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
				returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
						(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
						inputMessage, outputMessage);
				if (returnValue != null) {
					addContentDispositionHeader(inputMessage, outputMessage);
					((HttpMessageConverter<T>) messageConverter).write(returnValue,
							selectedMediaType, outputMessage);
					if (logger.isDebugEnabled()) {
						logger.debug("Written [" + returnValue + "] as \"" +
								selectedMediaType + "\" using [" + messageConverter + "]");
					}
				}
				return;
			}
		}
	}

	if (returnValue != null) {
		throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
	}
}