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