1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.stomp.websocket;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
21 import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;
22 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
23 import io.netty.handler.codec.http.websocketx.WebSocketFrame;
24 import io.netty.handler.codec.stomp.LastStompContentSubframe;
25 import io.netty.handler.codec.stomp.StompContentSubframe;
26 import io.netty.handler.codec.stomp.StompFrame;
27 import io.netty.handler.codec.stomp.StompHeaders;
28 import io.netty.handler.codec.stomp.StompHeadersSubframe;
29 import io.netty.handler.codec.stomp.StompSubframe;
30 import io.netty.handler.codec.stomp.StompSubframeEncoder;
31
32 import java.util.List;
33
34 public class StompWebSocketFrameEncoder extends StompSubframeEncoder {
35
36 @Override
37 public void encode(ChannelHandlerContext ctx, StompSubframe msg, List<Object> out) throws Exception {
38 super.encode(ctx, msg, out);
39 }
40
41 @Override
42 protected WebSocketFrame convertFullFrame(StompFrame original, ByteBuf encoded) {
43 if (isTextFrame(original)) {
44 return new TextWebSocketFrame(encoded);
45 }
46
47 return new BinaryWebSocketFrame(encoded);
48 }
49
50 @Override
51 protected WebSocketFrame convertHeadersSubFrame(StompHeadersSubframe original, ByteBuf encoded) {
52 if (isTextFrame(original)) {
53 return new TextWebSocketFrame(false, 0, encoded);
54 }
55
56 return new BinaryWebSocketFrame(false, 0, encoded);
57 }
58
59 @Override
60 protected WebSocketFrame convertContentSubFrame(StompContentSubframe original, ByteBuf encoded) {
61 if (original instanceof LastStompContentSubframe) {
62 return new ContinuationWebSocketFrame(true, 0, encoded);
63 }
64
65 return new ContinuationWebSocketFrame(false, 0, encoded);
66 }
67
68 private static boolean isTextFrame(StompHeadersSubframe headersSubframe) {
69 String contentType = headersSubframe.headers().getAsString(StompHeaders.CONTENT_TYPE);
70 return contentType != null && (contentType.startsWith("text") || contentType.startsWith("application/json"));
71 }
72 }