Example usage for org.springframework.http MediaType QUALITY_VALUE_COMPARATOR

List of usage examples for org.springframework.http MediaType QUALITY_VALUE_COMPARATOR

Introduction

In this page you can find the example usage for org.springframework.http MediaType QUALITY_VALUE_COMPARATOR.

Prototype

Comparator QUALITY_VALUE_COMPARATOR

To view the source code for org.springframework.http MediaType QUALITY_VALUE_COMPARATOR.

Click Source Link

Document

Comparator used by #sortByQualityValue(List) .

Usage

From source file:org.openrepose.filters.ratelimiting.RateLimitingHandler.java

private Optional<MediaType> getPreferredMediaType(List<String> acceptValues) {
    Optional<MediaType> preferredMediaType = Optional.of(DEFAULT_MEDIA_TYPE);
    if (!acceptValues.isEmpty()) {
        /*/*w  w  w  .  j a va2s .co m*/
         Parses and sorts (by specificity) media types from the "Accept" header (dropping any that cannot be parsed).
         This has intentionally been left separate from the stream processing below to avoid re-parsing
         and re-sorting accept media types for every supported media type.
          */
        List<MediaType> parsedAcceptMediaTypes = acceptValues.stream().map(RateLimitingHandler::parseMediaType)
                .filter(Optional::isPresent).map(Optional::get).sorted(MediaType.SPECIFICITY_COMPARATOR)
                .collect(Collectors.toList());

        /*
         For each supported media type, the most specific acceptable media type that is compatible is found.
         If no compatible acceptable media type if found, the supported media type will not be used.
         If the quality factor of the most specific acceptable media type compatible with a supported media type is
         set to 0, the supported media type will not be used.
                
         After discerning which supported media types are acceptable, sorts the acceptable media types by quality.
         The highest quality acceptable media type is then set as the preferred media type.
         */
        preferredMediaType = SUPPORTED_MEDIA_TYPES.stream()
                .map(supportedMediaType -> parsedAcceptMediaTypes.stream()
                        .filter(supportedMediaType::isCompatibleWith).findFirst()
                        .filter(acceptMediaType -> acceptMediaType.getQualityValue() != 0.0)
                        .map(acceptMediaType -> (Map.Entry<MediaType, MediaType>) new AbstractMap.SimpleEntry(
                                supportedMediaType, acceptMediaType)))
                .filter(Optional::isPresent).map(Optional::get)
                .sorted(Map.Entry.comparingByValue(MediaType.QUALITY_VALUE_COMPARATOR)).map(Map.Entry::getKey)
                .findFirst();
    }
    return preferredMediaType;
}