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