1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.websocket.common.extensions.fragment;
20
21
22 import java.io.IOException;
23 import java.nio.ByteBuffer;
24 import java.util.concurrent.Future;
25
26 import javax.net.websocket.SendResult;
27
28 import org.eclipse.jetty.websocket.api.WebSocketException;
29 import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig;
30 import org.eclipse.jetty.websocket.api.extensions.Frame;
31 import org.eclipse.jetty.websocket.common.OpCode;
32 import org.eclipse.jetty.websocket.common.WebSocketFrame;
33 import org.eclipse.jetty.websocket.common.extensions.AbstractExtension;
34
35
36
37
38 public class FragmentExtension extends AbstractExtension
39 {
40 private int maxLength = -1;
41
42 @Override
43 public void incomingError(WebSocketException e)
44 {
45
46 nextIncomingError(e);
47 }
48
49 @Override
50 public void incomingFrame(Frame frame)
51 {
52
53 nextIncomingFrame(frame);
54 }
55
56 @Override
57 public Future<SendResult> outgoingFrame(Frame frame) throws IOException
58 {
59 if (frame.getType().isControl())
60 {
61
62 return nextOutgoingFrame(frame);
63 }
64
65 int length = frame.getPayloadLength();
66
67 byte opcode = frame.getType().getOpCode();
68 ByteBuffer payload = frame.getPayload().slice();
69 int originalLimit = payload.limit();
70 int currentPosition = payload.position();
71
72 if (maxLength <= 0)
73 {
74
75 return nextOutgoingFrame(frame);
76 }
77
78 boolean continuation = false;
79
80
81 while (length > maxLength)
82 {
83 WebSocketFrame frag = new WebSocketFrame(frame);
84 frag.setOpCode(opcode);
85 frag.setFin(false);
86 frag.setContinuation(continuation);
87 payload.position(currentPosition);
88 payload.limit(Math.min(payload.position() + maxLength,originalLimit));
89 frag.setPayload(payload);
90
91 nextOutgoingFrame(frag);
92
93 length -= maxLength;
94 opcode = OpCode.CONTINUATION;
95 continuation = true;
96 currentPosition = payload.limit();
97 }
98
99
100 WebSocketFrame frag = new WebSocketFrame(frame);
101 frag.setOpCode(opcode);
102 frag.setFin(frame.isFin());
103 frag.setContinuation(continuation);
104 payload.position(currentPosition);
105 payload.limit(originalLimit);
106 frag.setPayload(payload);
107
108 return nextOutgoingFrame(frag);
109 }
110
111 @Override
112 public void setConfig(ExtensionConfig config)
113 {
114 super.setConfig(config);
115
116 maxLength = config.getParameter("maxLength",maxLength);
117 }
118 }