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 java.nio.charset.Charset; 020import java.nio.charset.StandardCharsets; 021 022import org.springframework.lang.Nullable; 023import org.springframework.messaging.Message; 024import org.springframework.messaging.MessageHeaders; 025import org.springframework.util.Assert; 026import org.springframework.util.MimeType; 027 028/** 029 * A {@link MessageConverter} that supports MIME type "text/plain" with the 030 * payload converted to and from a String. 031 * 032 * @author Rossen Stoyanchev 033 * @since 4.0 034 */ 035public class StringMessageConverter extends AbstractMessageConverter { 036 037 private final Charset defaultCharset; 038 039 040 public StringMessageConverter() { 041 this(StandardCharsets.UTF_8); 042 } 043 044 public StringMessageConverter(Charset defaultCharset) { 045 super(new MimeType("text", "plain", defaultCharset)); 046 Assert.notNull(defaultCharset, "Default Charset must not be null"); 047 this.defaultCharset = defaultCharset; 048 } 049 050 051 @Override 052 protected boolean supports(Class<?> clazz) { 053 return (String.class == clazz); 054 } 055 056 @Override 057 protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) { 058 Charset charset = getContentTypeCharset(getMimeType(message.getHeaders())); 059 Object payload = message.getPayload(); 060 return (payload instanceof String ? payload : new String((byte[]) payload, charset)); 061 } 062 063 @Override 064 @Nullable 065 protected Object convertToInternal( 066 Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) { 067 068 if (byte[].class == getSerializedPayloadClass()) { 069 Charset charset = getContentTypeCharset(getMimeType(headers)); 070 payload = ((String) payload).getBytes(charset); 071 } 072 return payload; 073 } 074 075 private Charset getContentTypeCharset(@Nullable MimeType mimeType) { 076 if (mimeType != null && mimeType.getCharset() != null) { 077 return mimeType.getCharset(); 078 } 079 else { 080 return this.defaultCharset; 081 } 082 } 083 084}