1 /* 2 * Copyright 2002-2014 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 package org.springframework.web.socket; 18 19 import java.nio.charset.Charset; 20 21 /** 22 * A text WebSocket message. 23 * 24 * @author Rossen Stoyanchev 25 * @since 4.0 26 */ 27 public final class TextMessage extends AbstractWebSocketMessage<String> { 28 29 private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); 30 31 private final byte[] bytes; 32 33 34 /** 35 * Create a new text WebSocket message from the given CharSequence payload. 36 * @param payload the non-null payload 37 */ 38 public TextMessage(CharSequence payload) { 39 super(payload.toString(), true); 40 this.bytes = null; 41 } 42 43 /** 44 * Create a new text WebSocket message from the given byte[]. It is assumed 45 * the byte array can be encoded into an UTF-8 String. 46 * @param payload the non-null payload 47 */ 48 public TextMessage(byte[] payload) { 49 super(new String(payload, UTF8_CHARSET)); 50 this.bytes = payload; 51 } 52 53 /** 54 * Create a new text WebSocket message with the given payload representing the 55 * full or partial message content. When the {@code isLast} boolean flag is set 56 * to {@code false} the message is sent as partial content and more partial 57 * messages will be expected until the boolean flag is set to {@code true}. 58 * @param payload the non-null payload 59 * @param isLast whether this the last part of a series of partial messages 60 */ 61 public TextMessage(CharSequence payload, boolean isLast) { 62 super(payload.toString(), isLast); 63 this.bytes = null; 64 } 65 66 67 @Override 68 public int getPayloadLength() { 69 return asBytes().length; 70 } 71 72 public byte[] asBytes() { 73 return (this.bytes != null ? this.bytes : getPayload().getBytes(UTF8_CHARSET)); 74 } 75 76 @Override 77 protected String toStringPayload() { 78 String payload = getPayload(); 79 return (payload.length() > 10 ? payload.substring(0, 10) + ".." : payload); 80 } 81 82 }