Minor tweaks to WebSocketMessage

- payload is now required
- byte data is obtained and stored only once (allowing multiple calls)
- minor formatting polish
This commit is contained in:
Phillip Webb 2013-04-23 12:08:55 -07:00
parent a14161f0ca
commit ff2e9aa5bc
3 changed files with 27 additions and 15 deletions

View File

@ -19,6 +19,8 @@ import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import org.springframework.util.Assert;
/**
* Represents a binary WebSocket message.
@ -28,7 +30,7 @@ import java.nio.ByteBuffer;
*/
public final class BinaryMessage extends WebSocketMessage<ByteBuffer> {
private final byte[] bytes;
private byte[] bytes;
private final boolean last;
@ -48,8 +50,19 @@ public final class BinaryMessage extends WebSocketMessage<ByteBuffer> {
}
public BinaryMessage(byte[] payload, boolean isLast) {
super((payload != null) ? ByteBuffer.wrap(payload) : null);
this.bytes = payload;
this(payload, 0, (payload == null ? 0 : payload.length), isLast);
}
public BinaryMessage(byte[] payload, int offset, int len) {
this(payload, offset, len, true);
}
public BinaryMessage(byte[] payload, int offset, int len, boolean isLast) {
super(payload != null ? ByteBuffer.wrap(payload, offset, len) : null);
if(payload != null && offset == 0 && len == payload.length) {
// FIXME better if a message always needs a payload?
this.bytes = payload;
}
this.last = isLast;
}
@ -58,17 +71,16 @@ public final class BinaryMessage extends WebSocketMessage<ByteBuffer> {
}
public byte[] getByteArray() {
if (this.bytes != null) {
return this.bytes;
}
else if (getPayload() != null){
byte[] result = new byte[getPayload().remaining()];
getPayload().get(result);
return result;
}
else {
return null;
if(this.bytes == null && getPayload() != null) {
this.bytes = getRemainingBytes(getPayload());
}
return this.bytes;
}
private byte[] getRemainingBytes(ByteBuffer payload) {
byte[] result = new byte[getPayload().remaining()];
getPayload().get(result);
return result;
}
public InputStream getInputStream() {

View File

@ -18,7 +18,6 @@ package org.springframework.websocket;
import java.io.Reader;
import java.io.StringReader;
/**
* Represents a text WebSocket message.
*
@ -27,7 +26,6 @@ import java.io.StringReader;
*/
public final class TextMessage extends WebSocketMessage<String> {
public TextMessage(String payload) {
super(payload);
}

View File

@ -15,6 +15,7 @@
*/
package org.springframework.websocket;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
@ -29,6 +30,7 @@ public abstract class WebSocketMessage<T> {
WebSocketMessage(T payload) {
Assert.notNull(payload, "Payload must not be null");
this.payload = payload;
}