01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.net.protocol.tcm;
05:
06: import com.tc.bytes.TCByteBuffer;
07: import com.tc.logging.TCLogger;
08: import com.tc.logging.TCLogging;
09: import com.tc.util.Assert;
10:
11: /**
12: * A class that knows how to parse TCMessages out of raw bytes
13: */
14: class TCMessageParser {
15: private static final TCLogger logger = TCLogging
16: .getLogger(TCMessageParser.class);
17: private final TCMessageFactory factory;
18:
19: TCMessageParser(TCMessageFactory factory) {
20: this .factory = factory;
21: }
22:
23: TCMessage parseMessage(MessageChannel source, TCByteBuffer[] data) {
24: TCMessageHeader hdr = new TCMessageHeaderImpl(data[0]
25: .duplicate().limit(TCMessageHeader.HEADER_LENGTH));
26: final int headerLength = hdr.getHeaderByteLength();
27:
28: if (headerLength != TCMessageHeader.HEADER_LENGTH) {
29: logger.error("Invalid header length ! length = "
30: + headerLength);
31: logger.error("error header = " + hdr);
32: logger.error(" buffer data is " + toString(data));
33: throw new RuntimeException("Invalid header length: "
34: + headerLength);
35: }
36:
37: final TCByteBuffer msgData[];
38:
39: if (data[0].limit() > headerLength) {
40: msgData = new TCByteBuffer[data.length];
41: System.arraycopy(data, 0, msgData, 0, msgData.length);
42: msgData[0] = msgData[0].position(headerLength).slice();
43: } else {
44: Assert.eval(data.length > 1);
45: msgData = new TCByteBuffer[data.length - 1];
46: System.arraycopy(data, 1, msgData, 0, msgData.length);
47: }
48:
49: final int msgType = hdr.getMessageType();
50: final TCMessageType type = TCMessageType.getInstance(hdr
51: .getMessageType());
52:
53: if (type == null) {
54: throw new RuntimeException(
55: "Can't find message type for type: " + msgType);
56: }
57:
58: return factory.createMessage(source, type, hdr, msgData);
59: }
60:
61: private String toString(TCByteBuffer[] data) {
62: if (data == null || data.length == 0) {
63: return "null or size 0";
64: }
65: StringBuffer sb = new StringBuffer();
66: for (int i = 0; i < data.length; i++) {
67: sb.append(data[i]);
68: sb.append(" { ");
69: byte b[] = data[i].array();
70: for (int j = 0; j < b.length; j++) {
71: sb.append(b[j]).append(" ");
72: }
73: sb.append(" } ");
74: }
75: return sb.toString();
76: }
77: }
|