use of org.apache.nifi.cluster.protocol.ProtocolMessageUnmarshaller in project nifi by apache.
the class JaxbProtocolContext method createUnmarshaller.
@Override
public ProtocolMessageUnmarshaller<T> createUnmarshaller() {
return new ProtocolMessageUnmarshaller<T>() {
@Override
public T unmarshal(final InputStream is) throws IOException {
try {
final DataInputStream dis = new DataInputStream(is);
// check for the presence of the message protocol sentinel
final byte sentinel = (byte) dis.read();
if (sentinel == -1) {
throw new EOFException();
}
if (MESSAGE_PROTOCOL_START_SENTINEL != sentinel) {
throw new IOException("Failed reading protocol message due to malformed header");
}
// read the message size
final int msgBytesSize = dis.readInt();
// read the message
final ByteBuffer buffer = ByteBuffer.allocate(msgBytesSize);
int totalBytesRead = 0;
do {
final int bytesToRead;
if ((msgBytesSize - totalBytesRead) >= BUF_SIZE) {
bytesToRead = BUF_SIZE;
} else {
bytesToRead = msgBytesSize - totalBytesRead;
}
totalBytesRead += dis.read(buffer.array(), totalBytesRead, bytesToRead);
} while (totalBytesRead < msgBytesSize);
// unmarshall message and return
final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
final byte[] msg = new byte[totalBytesRead];
buffer.get(msg);
final XMLStreamReader xsr = XmlUtils.createSafeReader(new ByteArrayInputStream(msg));
return (T) unmarshaller.unmarshal(xsr);
} catch (final JAXBException | XMLStreamException e) {
throw new IOException("Failed unmarshalling protocol message due to: " + e, e);
}
}
};
}
Aggregations