Example usage for org.springframework.http MediaType sortBySpecificityAndQuality

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

Introduction

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

Prototype

public static void sortBySpecificityAndQuality(List<MediaType> mediaTypes) 

Source Link

Document

Sorts the given list of MediaType objects by specificity as the primary criteria and quality value the secondary.

Usage

From source file:org.craftercms.commons.rest.HttpMessageConvertingResponseWriter.java

public <T> void writeWithMessageConverters(T returnValue, HttpServletRequest request,
        HttpServletResponse response) throws IOException, HttpMediaTypeNotAcceptableException {
    Class<?> returnValueClass = returnValue.getClass();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(returnValueClass);

    Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
    for (MediaType r : requestedMediaTypes) {
        for (MediaType p : producibleMediaTypes) {
            if (r.isCompatibleWith(p)) {
                compatibleMediaTypes.add(getMostSpecificMediaType(r, p));
            }//from  w ww . j  a  va2s .c o m
        }
    }
    if (compatibleMediaTypes.isEmpty()) {
        throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
    }

    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 : messageConverters) {
            if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
                ((HttpMessageConverter<T>) messageConverter).write(returnValue, selectedMediaType,
                        new ServletServerHttpResponse(response));

                logger.debug(LOG_KEY_WRITTEN_WITH_MESSAGE_CONVERTER, returnValue, selectedMediaType,
                        messageConverter);

                return;
            }
        }
    }

    throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
}

From source file:org.mitre.openid.connect.web.UserInfoEndpoint.java

/**
 * Get information about the user as specified in the accessToken included in this request
 *//* w  ww. j  a v  a  2 s  . co  m*/
@PreAuthorize("hasRole('ROLE_USER') and #oauth2.hasScope('" + SystemScopeService.OPENID_SCOPE + "')")
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, produces = {
        MediaType.APPLICATION_JSON_VALUE, UserInfoJWTView.JOSE_MEDIA_TYPE_VALUE })
public String getInfo(@RequestParam(value = "claims", required = false) String claimsRequestJsonString,
        @RequestHeader(value = HttpHeaders.ACCEPT, required = false) String acceptHeader,
        OAuth2Authentication auth, Model model) {

    if (auth == null) {
        logger.error("getInfo failed; no principal. Requester is not authorized.");
        model.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return HttpCodeView.VIEWNAME;
    }

    String username = auth.getName();
    UserInfo userInfo = userInfoService.getByUsernameAndClientId(username,
            auth.getOAuth2Request().getClientId());

    if (userInfo == null) {
        logger.error("getInfo failed; user not found: " + username);
        model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    model.addAttribute(UserInfoView.SCOPE, auth.getOAuth2Request().getScope());

    model.addAttribute(UserInfoView.AUTHORIZED_CLAIMS, auth.getOAuth2Request().getExtensions().get("claims"));

    if (!Strings.isNullOrEmpty(claimsRequestJsonString)) {
        model.addAttribute(UserInfoView.REQUESTED_CLAIMS, claimsRequestJsonString);
    }

    model.addAttribute(UserInfoView.USER_INFO, userInfo);

    // content negotiation

    // start off by seeing if the client has registered for a signed/encrypted JWT from here
    ClientDetailsEntity client = clientService.loadClientByClientId(auth.getOAuth2Request().getClientId());
    model.addAttribute(UserInfoJWTView.CLIENT, client);

    List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader);
    MediaType.sortBySpecificityAndQuality(mediaTypes);

    if (client.getUserInfoSignedResponseAlg() != null || client.getUserInfoEncryptedResponseAlg() != null
            || client.getUserInfoEncryptedResponseEnc() != null) {
        // client has a preference, see if they ask for plain JSON specifically on this request
        for (MediaType m : mediaTypes) {
            if (!m.isWildcardType() && m.isCompatibleWith(UserInfoJWTView.JOSE_MEDIA_TYPE)) {
                return UserInfoJWTView.VIEWNAME;
            } else if (!m.isWildcardType() && m.isCompatibleWith(MediaType.APPLICATION_JSON)) {
                return UserInfoView.VIEWNAME;
            }
        }

        // otherwise return JWT
        return UserInfoJWTView.VIEWNAME;
    } else {
        // client has no preference, see if they asked for JWT specifically on this request
        for (MediaType m : mediaTypes) {
            if (!m.isWildcardType() && m.isCompatibleWith(MediaType.APPLICATION_JSON)) {
                return UserInfoView.VIEWNAME;
            } else if (!m.isWildcardType() && m.isCompatibleWith(UserInfoJWTView.JOSE_MEDIA_TYPE)) {
                return UserInfoJWTView.VIEWNAME;
            }
        }

        // otherwise return JSON
        return UserInfoView.VIEWNAME;
    }

}

From source file:org.beadle.framework.view.ReturnTypeViewResolver.java

/**
 * Determines the list of {@link MediaType} for the given {@link HttpServletRequest}.
 * @param request the current servlet request
 * @return the list of media types requested, if any
 *///from w  w w. ja va2s  .c o  m
protected List<MediaType> getMediaTypes(HttpServletRequest request) {
    try {
        ServletWebRequest webRequest = new ServletWebRequest(request);

        List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest);
        acceptableMediaTypes = acceptableMediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL)
                : acceptableMediaTypes;

        List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request);
        Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
        for (MediaType acceptable : acceptableMediaTypes) {
            for (MediaType producible : producibleMediaTypes) {
                if (acceptable.isCompatibleWith(producible)) {
                    compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible));
                }
            }
        }
        List<MediaType> selectedMediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
        MediaType.sortBySpecificityAndQuality(selectedMediaTypes);
        if (logger.isDebugEnabled()) {
            logger.debug("Requested media types are " + selectedMediaTypes + " based on Accept header types "
                    + "and producible media types " + producibleMediaTypes + ")");
        }
        return selectedMediaTypes;
    } catch (HttpMediaTypeNotAcceptableException ex) {
        return null;
    }
}

From source file:org.fao.geonet.api.GlobalExceptionController.java

public List<MediaType> resolveMediaTypes(NativeWebRequest request) {

    String header = request.getHeader(HttpHeaders.ACCEPT);
    if (!StringUtils.hasText(header)) {
        return Collections.emptyList();
    }//from   w w  w  . j ava  2s  . c  o  m
    try {
        List<MediaType> mediaTypes = MediaType.parseMediaTypes(header);
        MediaType.sortBySpecificityAndQuality(mediaTypes);
        return mediaTypes;
    } catch (InvalidMediaTypeException ex) {
        return Collections.emptyList();
    }
}

From source file:org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerAdapter.java

private List<MediaType> getMediaTypes(HttpServletRequest request, Endpoint<?> endpoint, Class<?> resultClass)
        throws HttpMediaTypeNotAcceptableException {
    List<MediaType> requested = getAcceptableMediaTypes(request);
    List<MediaType> producible = getProducibleMediaTypes(endpoint, resultClass);

    Set<MediaType> compatible = new LinkedHashSet<MediaType>();
    for (MediaType r : requested) {
        for (MediaType p : producible) {
            if (r.isCompatibleWith(p)) {
                compatible.add(getMostSpecificMediaType(r, p));
            }//  w  ww  .  j a  v  a  2  s. c  om
        }
    }
    if (compatible.isEmpty()) {
        throw new HttpMediaTypeNotAcceptableException(producible);
    }
    List<MediaType> mediaTypes = new ArrayList<MediaType>(compatible);
    MediaType.sortBySpecificityAndQuality(mediaTypes);
    return mediaTypes;
}

From source file:org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler.java

/**
 * Predicate that checks whether the current request explicitly support
 * {@code "text/html"} media type./*from  w w  w .java  2s  . co  m*/
 * <p>
 * The "match-all" media type is not considered here.
 * @return the request predicate
 */
protected RequestPredicate acceptsTextHtml() {
    return (serverRequest) -> {
        try {
            List<MediaType> acceptedMediaTypes = serverRequest.headers().accept();
            acceptedMediaTypes.remove(MediaType.ALL);
            MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
            return acceptedMediaTypes.stream().anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
        } catch (InvalidMediaTypeException ex) {
            return false;
        }
    };
}

From source file:org.springframework.security.web.server.util.matcher.MediaTypeServerWebExchangeMatcher.java

private List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
    try {//from   w w  w  .  jav a2 s  .  co  m
        List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
        MediaType.sortBySpecificityAndQuality(mediaTypes);
        return mediaTypes;
    } catch (InvalidMediaTypeException ex) {
        String value = exchange.getRequest().getHeaders().getFirst("Accept");
        throw new NotAcceptableStatusException(
                "Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
    }
}

From source file:org.springframework.web.reactive.function.server.RequestPredicates.java

/**
 * Return a {@code RequestPredicate} that tests if the request's
 * {@linkplain ServerRequest.Headers#accept() accept} header is
 * {@linkplain MediaType#isCompatibleWith(MediaType) compatible} with any of the given media types.
 * @param mediaTypes the media types to match the request's accept header against
 * @return a predicate that tests the request's accept header against the given media types
 *//*from ww  w .  ja  v a2  s  . c o  m*/
public static RequestPredicate accept(MediaType... mediaTypes) {
    Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
    Set<MediaType> mediaTypeSet = new HashSet<>(Arrays.asList(mediaTypes));

    return headers(new Predicate<ServerRequest.Headers>() {
        @Override
        public boolean test(ServerRequest.Headers headers) {
            List<MediaType> acceptedMediaTypes = headers.accept();
            if (acceptedMediaTypes.isEmpty()) {
                acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
            } else {
                MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
            }
            boolean match = acceptedMediaTypes.stream().anyMatch(
                    acceptedMediaType -> mediaTypeSet.stream().anyMatch(acceptedMediaType::isCompatibleWith));
            traceMatch("Accept", mediaTypeSet, acceptedMediaTypes, match);
            return match;
        }

        @Override
        public String toString() {
            return String.format("Accept: %s", mediaTypeSet);
        }
    });
}

From source file:org.springframework.web.reactive.result.HandlerResultHandlerSupport.java

/**
 * Select the best media type for the current request through a content
 * negotiation algorithm./* w  ww  .ja va  2s .c o  m*/
 * @param exchange the current request
 * @param producibleTypesSupplier the media types that can be produced for the current request
 * @return the selected media type or {@code null}
 */
@Nullable
protected MediaType selectMediaType(ServerWebExchange exchange,
        Supplier<List<MediaType>> producibleTypesSupplier) {

    MediaType contentType = exchange.getResponse().getHeaders().getContentType();
    if (contentType != null && contentType.isConcrete()) {
        if (logger.isDebugEnabled()) {
            logger.debug(exchange.getLogPrefix() + "Found 'Content-Type:" + contentType + "' in response");
        }
        return contentType;
    }

    List<MediaType> acceptableTypes = getAcceptableTypes(exchange);
    List<MediaType> producibleTypes = getProducibleTypes(exchange, producibleTypesSupplier);

    Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
    for (MediaType acceptable : acceptableTypes) {
        for (MediaType producible : producibleTypes) {
            if (acceptable.isCompatibleWith(producible)) {
                compatibleMediaTypes.add(selectMoreSpecificMediaType(acceptable, producible));
            }
        }
    }

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

    MediaType selected = null;
    for (MediaType mediaType : result) {
        if (mediaType.isConcrete()) {
            selected = mediaType;
            break;
        } else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION_ALL)) {
            selected = MediaType.APPLICATION_OCTET_STREAM;
            break;
        }
    }

    if (selected != null) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Using '" + selected + "' given " + acceptableTypes + " and supported " + producibleTypes);
        }
    } else if (logger.isDebugEnabled()) {
        logger.debug(exchange.getLogPrefix() + "No match for " + acceptableTypes + ", supported: "
                + producibleTypes);
    }

    return selected;
}