public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
byte[] iv = getInitializationVector(exchange);
Key key = getKey(exchange);
CipherOutputStream cipherStream = new CipherOutputStream(outputStream, initializeCipher(ENCRYPT_MODE, key, iv));
InputStream plaintextStream = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
HMACAccumulator hmac = getMessageAuthenticationCode(key);
if (plaintextStream != null) {
inlineInitVector(outputStream, iv);
byte[] buffer = new byte[bufferSize];
int read;
try {
while ((read = plaintextStream.read(buffer)) > 0) {
cipherStream.write(buffer, 0, read);
cipherStream.flush();
hmac.encryptUpdate(buffer, read);
}
// only write if there is data to write (IBM JDK throws exception if no data)
byte[] mac = hmac.getCalculatedMac();
if (mac != null && mac.length > 0) {
cipherStream.write(mac);
}
} finally {
ObjectHelper.close(cipherStream, "cipher", LOG);
}
}