forked from rabbitmq/rabbitmq-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrame.java
More file actions
355 lines (316 loc) · 11.5 KB
/
Frame.java
File metadata and controls
355 lines (316 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (c) 2007-Present Pivotal Software, Inc. All rights reserved.
//
// This software, the RabbitMQ Java client library, is triple-licensed under the
// Mozilla Public License 1.1 ("MPL"), the GNU General Public License version 2
// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see
// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL,
// please see LICENSE-APACHE2.
//
// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
// either express or implied. See the LICENSE file for specific language governing
// rights and limitations of this software.
//
// If you have any questions regarding licensing, please contact us at
// info@rabbitmq.com.
package com.rabbitmq.client.impl;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.LongString;
import com.rabbitmq.client.MalformedFrameException;
import java.io.*;
import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Represents an AMQP wire-protocol frame, with frame type, channel number, and payload bytes.
*/
public class Frame {
/** Frame type code */
private final int type;
/** Frame channel number, 0-65535 */
private final int channel;
/** Frame payload bytes (for inbound frames) */
private final byte[] payload;
/** Frame payload (for outbound frames) */
private final ByteArrayOutputStream accumulator;
private static final int NON_BODY_SIZE = 1 /* type */ + 2 /* channel */ + 4 /* payload size */ + 1 /* end character */;
/**
* Constructs a frame for output with a type and a channel number and a
* fresh accumulator waiting for payload.
*/
public Frame(int type, int channel) {
this.type = type;
this.channel = channel;
this.payload = null;
this.accumulator = new ByteArrayOutputStream();
}
/**
* Constructs a frame for input with a type, a channel number and a
* payload byte array.
*/
public Frame(int type, int channel, byte[] payload) {
this.type = type;
this.channel = channel;
this.payload = payload;
this.accumulator = null;
}
public static Frame fromBodyFragment(int channelNumber, byte[] body, int offset, int length)
throws IOException
{
Frame frame = new Frame(AMQP.FRAME_BODY, channelNumber);
DataOutputStream bodyOut = frame.getOutputStream();
bodyOut.write(body, offset, length);
return frame;
}
/**
* Protected API - Factory method to instantiate a Frame by reading an
* AMQP-wire-protocol frame from the given input stream.
*
* @return a new Frame if we read a frame successfully, otherwise null
*/
public static Frame readFrom(DataInputStream is) throws IOException {
int type;
int channel;
try {
type = is.readUnsignedByte();
} catch (SocketTimeoutException ste) {
// System.err.println("Timed out waiting for a frame.");
return null; // failed
}
if (type == 'A') {
/*
* Probably an AMQP.... header indicating a version
* mismatch.
*/
/*
* Otherwise meaningless, so try to read the version,
* and throw an exception, whether we read the version
* okay or not.
*/
protocolVersionMismatch(is);
}
channel = is.readUnsignedShort();
int payloadSize = is.readInt();
byte[] payload = new byte[payloadSize];
is.readFully(payload);
int frameEndMarker = is.readUnsignedByte();
if (frameEndMarker != AMQP.FRAME_END) {
throw new MalformedFrameException("Bad frame end marker: " + frameEndMarker);
}
return new Frame(type, channel, payload);
}
/**
* Private API - A protocol version mismatch is detected by checking the
* three next bytes if a frame type of (int)'A' is read from an input
* stream. If the next three bytes are 'M', 'Q' and 'P', then it's
* likely the broker is trying to tell us we are speaking the wrong AMQP
* protocol version.
*
* @throws MalformedFrameException
* if an AMQP protocol version mismatch is detected
* @throws MalformedFrameException
* if a corrupt AMQP protocol identifier is read
*/
public static void protocolVersionMismatch(DataInputStream is) throws IOException {
MalformedFrameException x;
// We expect the letters M, Q, P in that order: generate an informative error if they're not found
byte[] expectedBytes = new byte[] { 'M', 'Q', 'P' };
for (byte expectedByte : expectedBytes) {
int nextByte = is.readUnsignedByte();
if (nextByte != expectedByte) {
throw new MalformedFrameException("Invalid AMQP protocol header from server: expected character " +
expectedByte + ", got " + nextByte);
}
}
try {
int[] signature = new int[4];
for (int i = 0; i < 4; i++) {
signature[i] = is.readUnsignedByte();
}
if (signature[0] == 1 &&
signature[1] == 1 &&
signature[2] == 8 &&
signature[3] == 0) {
x = new MalformedFrameException("AMQP protocol version mismatch; we are version " +
AMQP.PROTOCOL.MAJOR + "-" + AMQP.PROTOCOL.MINOR + "-" + AMQP.PROTOCOL.REVISION +
", server is 0-8");
}
else {
String sig = "";
for (int i = 0; i < 4; i++) {
if (i != 0) sig += ",";
sig += signature[i];
}
x = new MalformedFrameException("AMQP protocol version mismatch; we are version " +
AMQP.PROTOCOL.MAJOR + "-" + AMQP.PROTOCOL.MINOR + "-" + AMQP.PROTOCOL.REVISION +
", server sent signature " + sig);
}
} catch (IOException ex) {
x = new MalformedFrameException("Invalid AMQP protocol header from server");
}
throw x;
}
/**
* Public API - writes this Frame to the given DataOutputStream
*/
public void writeTo(DataOutputStream os) throws IOException {
os.writeByte(type);
os.writeShort(channel);
if (accumulator != null) {
os.writeInt(accumulator.size());
accumulator.writeTo(os);
} else {
os.writeInt(payload.length);
os.write(payload);
}
os.write(AMQP.FRAME_END);
}
public int size() {
if(accumulator != null) {
return accumulator.size() + NON_BODY_SIZE;
} else {
return payload.length + NON_BODY_SIZE;
}
}
/**
* Public API - retrieves the frame payload
*/
public byte[] getPayload() {
if (payload != null) return payload;
// This is a Frame we've constructed ourselves. For some reason (e.g.
// testing), we're acting as if we received it even though it
// didn't come in off the wire.
return accumulator.toByteArray();
}
/**
* Public API - retrieves a new DataInputStream streaming over the payload
*/
public DataInputStream getInputStream() {
return new DataInputStream(new ByteArrayInputStream(getPayload()));
}
/**
* Public API - retrieves a fresh DataOutputStream streaming into the accumulator
*/
public DataOutputStream getOutputStream() {
return new DataOutputStream(accumulator);
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Frame(type=").append(type).append(", channel=").append(channel).append(", ");
if (accumulator == null) {
sb.append(payload.length).append(" bytes of payload)");
} else {
sb.append(accumulator.size()).append(" bytes of accumulator)");
}
return sb.toString();
}
/** Computes the AMQP wire-protocol length of protocol-encoded table entries.
*/
public static long tableSize(Map<String, Object> table)
throws UnsupportedEncodingException
{
long acc = 0;
for(Map.Entry<String, Object> entry: table.entrySet()) {
acc += shortStrSize(entry.getKey());
acc += fieldValueSize(entry.getValue());
}
return acc;
}
/** Computes the AMQP wire-protocol length of a protocol-encoded field-value. */
private static long fieldValueSize(Object value)
throws UnsupportedEncodingException
{
long acc = 1; // for the type tag
if(value instanceof String) {
acc += longStrSize((String)value);
}
else if(value instanceof LongString) {
acc += 4 + ((LongString)value).length();
}
else if(value instanceof Integer) {
acc += 4;
}
else if(value instanceof BigDecimal) {
acc += 5;
}
else if(value instanceof Date || value instanceof Timestamp) {
acc += 8;
}
else if(value instanceof Map) {
@SuppressWarnings("unchecked")
Map<String,Object> map = (Map<String,Object>) value;
acc += 4 + tableSize(map);
}
else if (value instanceof Byte) {
acc += 1;
}
else if(value instanceof Double) {
acc += 8;
}
else if(value instanceof Float) {
acc += 4;
}
else if(value instanceof Long) {
acc += 8;
}
else if(value instanceof Short) {
acc += 2;
}
else if(value instanceof Boolean) {
acc += 1;
}
else if(value instanceof byte[]) {
acc += 4 + ((byte[])value).length;
}
else if(value instanceof List) {
acc += 4 + arraySize((List<?>)value);
}
else if(value instanceof Object[]) {
acc += 4 + arraySize((Object[])value);
}
else if(value == null) {
}
else {
throw new IllegalArgumentException("invalid value in table");
}
return acc;
}
/** Computes the AMQP 0-9-1 wire-protocol length of an encoded field-array of type List */
public static long arraySize(List<?> values)
throws UnsupportedEncodingException
{
long acc = 0;
for (Object value : values) {
acc += fieldValueSize(value);
}
return acc;
}
/** Computes the AMQP wire-protocol length of an encoded field-array of type Object[] */
public static long arraySize(Object[] values) throws UnsupportedEncodingException {
long acc = 0;
for (Object value : values) {
acc += fieldValueSize(value);
}
return acc;
}
/** Computes the AMQP wire-protocol length of a protocol-encoded long string. */
private static int longStrSize(String str)
throws UnsupportedEncodingException
{
return str.getBytes("utf-8").length + 4;
}
/** Computes the AMQP wire-protocol length of a protocol-encoded short string. */
private static int shortStrSize(String str)
throws UnsupportedEncodingException
{
return str.getBytes("utf-8").length + 1;
}
public int getType() {
return type;
}
public int getChannel() {
return channel;
}
}