String blockKey = firstNewBlockKey;
for (int n = 1; n != numFullBlocks; ++n) {
// Create the sublist of children that should be written to a new block ...
boolean isLast = n == (numFullBlocks - 1);
endIndex = isLast ? total : (startIndex + targetCountPerBlock);
EditableArray blockChildren = Schematic.newArray(children.subList(startIndex, endIndex));
// Create the new block, with a key that contains a UUID for the identifier ...
String nextBlockKey = (isLast) ? nextBlockKey = nextBlock : key.withRandomId().toString();
EditableDocument blockDoc = Schematic.newDocument();
EditableDocument childInfo = blockDoc.setDocument(CHILDREN_INFO);
childInfo.setNumber(BLOCK_SIZE, blockChildren.size());
if (nextBlockKey != null) {
childInfo.setString(NEXT_BLOCK, nextBlockKey);
}
// Write the children ...
blockDoc.setArray(CHILDREN, blockChildren);
// Now persist the new document ...
documentStore.localStore().put(blockKey, blockDoc);
// And get ready for the next block ...
if (!isLast) {
blockKey = nextBlockKey;
startIndex = endIndex;
}
}
// Now we can update the input document's children and nextBlock reference ...
EditableArray newChildren = Schematic.newArray(children.subList(0, targetCountPerBlock));
document.setArray(CHILDREN, newChildren);
EditableDocument childInfo = document.getDocument(CHILDREN_INFO);
if (childInfo == null) {
childInfo = document.setDocument(CHILDREN_INFO);
}
childInfo.setNumber(BLOCK_SIZE, newChildren.size());
childInfo.setString(NEXT_BLOCK, firstNewBlockKey);
if (isFirst && nextBlock == null) {
// We generated a new last block and we have to update the reference ...
childInfo.setString(LAST_BLOCK, blockKey);