001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package com.tc.net.protocol.tcm;
005:
006: import com.tc.bytes.TCByteBuffer;
007: import com.tc.net.protocol.AbstractTCNetworkHeader;
008: import com.tc.net.protocol.TCProtocolException;
009: import com.tc.util.Assert;
010:
011: /**
012: * TODO: document me
013: *
014: * @author teck
015: */
016: public class TCMessageHeaderImpl extends AbstractTCNetworkHeader
017: implements TCMessageHeader {
018: // TODO: This class (and other network headers) should be auto-generated from some form of definition file
019:
020: protected TCMessageHeaderImpl(TCByteBuffer hdrData) {
021: super (hdrData, MIN_LENGTH, MAX_LENGTH);
022: }
023:
024: TCMessageHeaderImpl(TCMessageType type) {
025: super (MIN_LENGTH, MAX_LENGTH);
026:
027: setMessageType(type.getType());
028: setVersion(VERSION_1);
029: setHeaderLength((short) (MIN_LENGTH / 4));
030: }
031:
032: public int getHeaderByteLength() {
033: return getHeaderLength() * 4;
034: }
035:
036: public short getVersion() {
037: return data.getUbyte(0);
038: }
039:
040: public int getHeaderLength() {
041: return data.getUbyte(1);
042: }
043:
044: public int getMessageType() {
045: return data.getUshort(2);
046: }
047:
048: public int getMessageTypeVersion() {
049: return data.getUshort(4);
050: }
051:
052: void setVersion(short version) {
053: data.putUbyte(0, version);
054: }
055:
056: protected void setHeaderLength(short length) {
057: Assert.eval(length <= MAX_LENGTH);
058: data.putUbyte(1, length);
059: }
060:
061: public void setMessageType(int type) {
062: data.putUshort(2, type);
063: }
064:
065: public void setMessageTypeVersion(int version) {
066: data.putUshort(4, version);
067: }
068:
069: public String toString() {
070: StringBuffer buf = new StringBuffer();
071:
072: TCMessageType type = TCMessageType
073: .getInstance(getMessageType());
074:
075: buf.append("msgType: ");
076: if (type != null) {
077: buf.append(type.toString());
078: } else {
079: buf.append("UNKNOWN").append('(').append(getMessageType())
080: .append(')');
081: }
082:
083: buf.append(", msgVer=").append(getMessageTypeVersion());
084: buf.append('\n');
085:
086: return buf.toString();
087: }
088:
089: public void validate() throws TCProtocolException {
090: final short version = getVersion();
091: final short expect = VERSION_1;
092: if (version != expect) {
093: throw new TCProtocolException("Version " + version
094: + " does not match expected version " + expect);
095: }
096:
097: // XXX: validate other fields
098: }
099:
100: protected boolean isHeaderLengthAvail() {
101: return data.position() > 1;
102: }
103:
104: }
|