* @param arr this is the buffer for the frame
* @param offset this is where to start reading in the buffer for this field
*/
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException {
if (offset >= arr.length) {
throw new InvalidDataTypeException("Unable to find null terminated string");
}
int bufferSize;
//
//logger.finer("Reading from array starting from offset:" + offset);
int size;
//Get the Specified Decoder
String charSetName = getTextEncodingCharSet();
CharsetDecoder decoder = Charset.forName(charSetName).newDecoder();
//We only want to load up to null terminator, data after this is part of different
//field and it may not be possible to decode it so do the check before we do
//do the decoding,encoding dependent.
ByteBuffer buffer = ByteBuffer.wrap(arr, offset, arr.length - offset);
int endPosition = 0;
//Latin-1 and UTF-8 strings are terminated by a single-byte null,
//while UTF-16 and its variants need two bytes for the null terminator.
final boolean nullIsOneByte = (charSetName.equals(TextEncoding.CHARSET_ISO_8859_1) || charSetName.equals(TextEncoding.CHARSET_UTF_8));
boolean isNullTerminatorFound = false;
while (buffer.hasRemaining()) {
byte nextByte = buffer.get();
if (nextByte == 0x00) {
if (nullIsOneByte) {
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 1;
// logger.finest("Null terminator found starting at:" + endPosition);
isNullTerminatorFound = true;
break;
} else {
// Looking for two-byte null
if (buffer.hasRemaining()) {
nextByte = buffer.get();
if (nextByte == 0x00) {
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 2;
// logger.finest("UTF16:Null terminator found starting at:" + endPosition);
isNullTerminatorFound = true;
break;
} else {
//Nothing to do, we have checked 2nd value of pair it was not a null terminator
//so will just start looking again in next invocation of loop
}
} else {
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 1;
//logger.warning("UTF16:Should be two null terminator marks but only found one starting at:" + endPosition);
isNullTerminatorFound = true;
break;
}
}
} else {
//If UTF16, we should only be looking on 2 byte boundaries
if (!nullIsOneByte) {
if (buffer.hasRemaining()) {
buffer.get();
}
}
}
}
if (!isNullTerminatorFound) {
throw new InvalidDataTypeException("Unable to find null terminated string");
}
//
//logger.finest("End Position is:" + endPosition + "Offset:" + offset);