001/* 002 * Copyright 2002-2020 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.server; 018 019import java.util.Collections; 020import java.util.List; 021import java.util.Map; 022 023import org.springframework.http.HttpHeaders; 024import org.springframework.http.HttpStatus; 025import org.springframework.http.MediaType; 026import org.springframework.util.CollectionUtils; 027 028/** 029 * Exception for errors that fit response status 406 (not acceptable). 030 * 031 * @author Rossen Stoyanchev 032 * @since 5.0 033 */ 034@SuppressWarnings("serial") 035public class NotAcceptableStatusException extends ResponseStatusException { 036 037 private final List<MediaType> supportedMediaTypes; 038 039 040 /** 041 * Constructor for when the requested Content-Type is invalid. 042 */ 043 public NotAcceptableStatusException(String reason) { 044 super(HttpStatus.NOT_ACCEPTABLE, reason); 045 this.supportedMediaTypes = Collections.emptyList(); 046 } 047 048 /** 049 * Constructor for when the requested Content-Type is not supported. 050 */ 051 public NotAcceptableStatusException(List<MediaType> supportedMediaTypes) { 052 super(HttpStatus.NOT_ACCEPTABLE, "Could not find acceptable representation"); 053 this.supportedMediaTypes = Collections.unmodifiableList(supportedMediaTypes); 054 } 055 056 057 /** 058 * Return a Map with an "Accept" header. 059 * @since 5.1.11 060 */ 061 @SuppressWarnings("deprecation") 062 @Override 063 public Map<String, String> getHeaders() { 064 return getResponseHeaders().toSingleValueMap(); 065 } 066 067 /** 068 * Return HttpHeaders with an "Accept" header, or an empty instance. 069 * @since 5.1.13 070 */ 071 @Override 072 public HttpHeaders getResponseHeaders() { 073 if (CollectionUtils.isEmpty(this.supportedMediaTypes)) { 074 return HttpHeaders.EMPTY; 075 } 076 HttpHeaders headers = new HttpHeaders(); 077 headers.setAccept(this.supportedMediaTypes); 078 return headers; 079 } 080 081 /** 082 * Return the list of supported content types in cases when the Accept 083 * header is parsed but not supported, or an empty list otherwise. 084 */ 085 public List<MediaType> getSupportedMediaTypes() { 086 return this.supportedMediaTypes; 087 } 088 089}