if (!pdu.hasCommandLengthCalculated()) {
pdu.calculateAndSetCommandLength();
}
// create the buffer and add the header
ChannelBuffer buffer = new BigEndianHeapChannelBuffer(pdu.getCommandLength());
buffer.writeInt(pdu.getCommandLength());
buffer.writeInt(pdu.getCommandId());
buffer.writeInt(pdu.getCommandStatus());
buffer.writeInt(pdu.getSequenceNumber());
// add mandatory body (a noop if no body exists)
pdu.writeBody(buffer);
// add optional parameters (a noop if none exist)
pdu.writeOptionalParameters(buffer, context);
// NOTE: at this point, the entire buffer written MUST match the command length
// from earlier -- if it doesn't match, the our encoding process went awry
if (buffer.readableBytes() != pdu.getCommandLength()) {
throw new NotEnoughDataInBufferException("During PDU encoding the expected commandLength did not match the actual encoded (a serious error with our own encoding process)", pdu.getCommandLength(), buffer.readableBytes());
}
return buffer;
}