public final class TransformerCondition implements Condition {
@Override
public boolean check() {
try {
CompositeBuffer savedBuffer = inputBufferAttr.get(attributeStorage);
Buffer bufferToTransform = savedBuffer;
Buffer chunkBuffer;
final boolean hasSavedBuffer = (savedBuffer != null);
if (underlyingInput.isBuffered()) {
chunkBuffer = underlyingInput.takeBuffer();
} else {
int size = underlyingInput.size();
chunkBuffer = memoryManager.allocate(size);
while (size-- >= 0) {
chunkBuffer.put(underlyingInput.read());
}
chunkBuffer.flip();
}
if (hasSavedBuffer) {
savedBuffer.append(chunkBuffer);
} else {
bufferToTransform = chunkBuffer;
}
while (bufferToTransform.hasRemaining()) {
final TransformationResult<Buffer, Buffer> result =
transformer.transform(attributeStorage,
bufferToTransform);
final Status status = result.getStatus();
if (status == Status.COMPLETE) {
final Buffer outputBuffer = result.getMessage();
lock.writeLock().lock();
try {
append(outputBuffer);
if (!isCompletionHandlerRegistered) {
// if !isCompletionHandlerRegistered - it means StreamReader has enough data to continue processing
return true;
}
} finally {
lock.writeLock().unlock();
}
} else if (status == Status.INCOMPLETE) {
if (!hasSavedBuffer) {
if (bufferToTransform.isComposite()) {
inputBufferAttr.set(attributeStorage,
(CompositeBuffer) bufferToTransform);
} else {
savedBuffer = CompositeBuffer.newBuffer(memoryManager);
savedBuffer.append(bufferToTransform);
inputBufferAttr.set(attributeStorage, savedBuffer);
}
}
return false;