1 /* 2 * Copyright 2002-2017 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 module hunt.stomp.converter.DefaultContentTypeResolver; 18 19 import hunt.stomp.converter.ContentTypeResolver; 20 import hunt.stomp.MessageHeaders; 21 import hunt.util.MimeType; 22 23 import hunt.Exceptions; 24 import hunt.Nullable; 25 import hunt.String; 26 27 /** 28 * A default {@link ContentTypeResolver} that checks the 29 * {@link MessageHeaders#CONTENT_TYPE} header or falls back to a default value. 30 * 31 * <p>The header value is expected to be a {@link hunt.framework.util.MimeType} 32 * or a {@code string} that can be parsed into a {@code MimeType}. 33 * 34 * @author Rossen Stoyanchev 35 * @since 4.0 36 */ 37 class DefaultContentTypeResolver : ContentTypeResolver { 38 39 private MimeType defaultMimeType; 40 41 42 /** 43 * Set the default MIME type to use when there is no 44 * {@link MessageHeaders#CONTENT_TYPE} header present. 45 * <p>This property does not have a default value. 46 */ 47 void setDefaultMimeType(MimeType defaultMimeType) { 48 this.defaultMimeType = defaultMimeType; 49 } 50 51 /** 52 * Return the default MIME type to use if no 53 * {@link MessageHeaders#CONTENT_TYPE} header is present. 54 */ 55 56 MimeType getDefaultMimeType() { 57 return this.defaultMimeType; 58 } 59 60 61 override 62 63 MimeType resolve(MessageHeaders headers) { 64 if (headers is null || headers.get(MessageHeaders.CONTENT_TYPE) is null) { 65 return this.defaultMimeType; 66 } 67 68 Object value = headers.get(MessageHeaders.CONTENT_TYPE); 69 if (value is null) { 70 return null; 71 } 72 73 MimeType mt = cast(MimeType) value; 74 if (mt !is null) { 75 return mt; 76 } 77 78 String strObject = cast(String)value; 79 if (strObject !is null) { 80 return new MimeType(strObject.value); 81 } 82 83 throw new IllegalArgumentException( 84 "Unknown type for contentType header value: " ~ typeid(value).toString()); 85 } 86 87 override 88 string toString() { 89 return "DefaultContentTypeResolver[" ~ "defaultMimeType=" ~ 90 this.defaultMimeType.toString() ~ "]"; 91 } 92 93 }