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.nio.ByteBuffer;
23
24 import org.eclipse.jetty.websocket.api.WebSocketException;
25 import org.eclipse.jetty.websocket.api.WriteCallback;
26 import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig;
27 import org.eclipse.jetty.websocket.api.extensions.Frame;
28 import org.eclipse.jetty.websocket.common.OpCode;
29 import org.eclipse.jetty.websocket.common.WebSocketFrame;
30 import org.eclipse.jetty.websocket.common.extensions.AbstractExtension;
31
32
33
34
35 public class FragmentExtension extends AbstractExtension
36 {
37 private int maxLength = -1;
38
39 @Override
40 public void incomingError(WebSocketException e)
41 {
42
43 nextIncomingError(e);
44 }
45
46 @Override
47 public void incomingFrame(Frame frame)
48 {
49
50 nextIncomingFrame(frame);
51 }
52
53 @Override
54 public void outgoingFrame(Frame frame, WriteCallback callback)
55 {
56 if (frame.getType().isControl())
57 {
58
59 nextOutgoingFrame(frame,callback);
60 return;
61 }
62
63 int length = frame.getPayloadLength();
64
65 byte opcode = frame.getType().getOpCode();
66 ByteBuffer payload = frame.getPayload().slice();
67 int originalLimit = payload.limit();
68 int currentPosition = payload.position();
69
70 if (maxLength <= 0)
71 {
72
73 nextOutgoingFrame(frame,callback);
74 return;
75 }
76
77 boolean continuation = false;
78
79
80 while (length > maxLength)
81 {
82 WebSocketFrame frag = new WebSocketFrame(frame);
83 frag.setOpCode(opcode);
84 frag.setFin(false);
85 frag.setContinuation(continuation);
86 payload.position(currentPosition);
87 payload.limit(Math.min(payload.position() + maxLength,originalLimit));
88 frag.setPayload(payload);
89
90
91 nextOutgoingFrame(frag,null);
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 nextOutgoingFrame(frag,callback);
109 }
110
111 @Override
112 public void setConfig(ExtensionConfig config)
113 {
114 super.setConfig(config);
115
116 maxLength = config.getParameter("maxLength",maxLength);
117 }
118 }