001/*
002 * Copyright 2002-2016 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.accept;
018
019import java.util.Arrays;
020import java.util.Collections;
021import java.util.List;
022
023import org.springframework.http.HttpHeaders;
024import org.springframework.http.InvalidMediaTypeException;
025import org.springframework.http.MediaType;
026import org.springframework.web.HttpMediaTypeNotAcceptableException;
027import org.springframework.web.context.request.NativeWebRequest;
028
029/**
030 * A {@code ContentNegotiationStrategy} that checks the 'Accept' request header.
031 *
032 * @author Rossen Stoyanchev
033 * @author Juergen Hoeller
034 * @since 3.2
035 */
036public class HeaderContentNegotiationStrategy implements ContentNegotiationStrategy {
037
038        /**
039         * {@inheritDoc}
040         * @throws HttpMediaTypeNotAcceptableException if the 'Accept' header cannot be parsed
041         */
042        @Override
043        public List<MediaType> resolveMediaTypes(NativeWebRequest request)
044                        throws HttpMediaTypeNotAcceptableException {
045
046                String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT);
047                if (headerValueArray == null) {
048                        return Collections.<MediaType>emptyList();
049                }
050
051                List<String> headerValues = Arrays.asList(headerValueArray);
052                try {
053                        List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues);
054                        MediaType.sortBySpecificityAndQuality(mediaTypes);
055                        return mediaTypes;
056                }
057                catch (InvalidMediaTypeException ex) {
058                        throw new HttpMediaTypeNotAcceptableException(
059                                        "Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage());
060                }
061        }
062
063}