001/* 002 * Copyright 2002-2017 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.messaging.converter; 018 019import org.springframework.lang.Nullable; 020import org.springframework.messaging.MessageHeaders; 021import org.springframework.util.MimeType; 022 023/** 024 * A default {@link ContentTypeResolver} that checks the 025 * {@link MessageHeaders#CONTENT_TYPE} header or falls back to a default value. 026 * 027 * <p>The header value is expected to be a {@link org.springframework.util.MimeType} 028 * or a {@code String} that can be parsed into a {@code MimeType}. 029 * 030 * @author Rossen Stoyanchev 031 * @since 4.0 032 */ 033public class DefaultContentTypeResolver implements ContentTypeResolver { 034 035 @Nullable 036 private MimeType defaultMimeType; 037 038 039 /** 040 * Set the default MIME type to use when there is no 041 * {@link MessageHeaders#CONTENT_TYPE} header present. 042 * <p>This property does not have a default value. 043 */ 044 public void setDefaultMimeType(@Nullable MimeType defaultMimeType) { 045 this.defaultMimeType = defaultMimeType; 046 } 047 048 /** 049 * Return the default MIME type to use if no 050 * {@link MessageHeaders#CONTENT_TYPE} header is present. 051 */ 052 @Nullable 053 public MimeType getDefaultMimeType() { 054 return this.defaultMimeType; 055 } 056 057 058 @Override 059 @Nullable 060 public MimeType resolve(@Nullable MessageHeaders headers) { 061 if (headers == null || headers.get(MessageHeaders.CONTENT_TYPE) == null) { 062 return this.defaultMimeType; 063 } 064 Object value = headers.get(MessageHeaders.CONTENT_TYPE); 065 if (value == null) { 066 return null; 067 } 068 else if (value instanceof MimeType) { 069 return (MimeType) value; 070 } 071 else if (value instanceof String) { 072 return MimeType.valueOf((String) value); 073 } 074 else { 075 throw new IllegalArgumentException( 076 "Unknown type for contentType header value: " + value.getClass()); 077 } 078 } 079 080 @Override 081 public String toString() { 082 return "DefaultContentTypeResolver[" + "defaultMimeType=" + this.defaultMimeType + "]"; 083 } 084 085}