001/* 002 * Copyright 2002-2014 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.web.socket; 018 019import java.nio.charset.Charset; 020 021/** 022 * A text WebSocket message. 023 * 024 * @author Rossen Stoyanchev 025 * @since 4.0 026 */ 027public final class TextMessage extends AbstractWebSocketMessage<String> { 028 029 private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); 030 031 private final byte[] bytes; 032 033 034 /** 035 * Create a new text WebSocket message from the given CharSequence payload. 036 * @param payload the non-null payload 037 */ 038 public TextMessage(CharSequence payload) { 039 super(payload.toString(), true); 040 this.bytes = null; 041 } 042 043 /** 044 * Create a new text WebSocket message from the given byte[]. It is assumed 045 * the byte array can be encoded into an UTF-8 String. 046 * @param payload the non-null payload 047 */ 048 public TextMessage(byte[] payload) { 049 super(new String(payload, UTF8_CHARSET)); 050 this.bytes = payload; 051 } 052 053 /** 054 * Create a new text WebSocket message with the given payload representing the 055 * full or partial message content. When the {@code isLast} boolean flag is set 056 * to {@code false} the message is sent as partial content and more partial 057 * messages will be expected until the boolean flag is set to {@code true}. 058 * @param payload the non-null payload 059 * @param isLast whether this the last part of a series of partial messages 060 */ 061 public TextMessage(CharSequence payload, boolean isLast) { 062 super(payload.toString(), isLast); 063 this.bytes = null; 064 } 065 066 067 @Override 068 public int getPayloadLength() { 069 return asBytes().length; 070 } 071 072 public byte[] asBytes() { 073 return (this.bytes != null ? this.bytes : getPayload().getBytes(UTF8_CHARSET)); 074 } 075 076 @Override 077 protected String toStringPayload() { 078 String payload = getPayload(); 079 return (payload.length() > 10 ? payload.substring(0, 10) + ".." : payload); 080 } 081 082}