001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.reactive.accept;
018
019import java.util.List;
020
021import org.springframework.http.InvalidMediaTypeException;
022import org.springframework.http.MediaType;
023import org.springframework.util.CollectionUtils;
024import org.springframework.web.server.NotAcceptableStatusException;
025import org.springframework.web.server.ServerWebExchange;
026
027/**
028 * Resolver that looks at the 'Accept' header of the request.
029 *
030 * @author Rossen Stoyanchev
031 * @since 5.0
032 */
033public class HeaderContentTypeResolver implements RequestedContentTypeResolver {
034
035        @Override
036        public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
037                try {
038                        List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
039                        MediaType.sortBySpecificityAndQuality(mediaTypes);
040                        return (!CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST);
041                }
042                catch (InvalidMediaTypeException ex) {
043                        String value = exchange.getRequest().getHeaders().getFirst("Accept");
044                        throw new NotAcceptableStatusException(
045                                        "Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
046                }
047        }
048
049}