final String originalText = node.getTextContent();
int startIndex = 0;
while ((startIndex = originalText.indexOf(entityPlaceholder, startIndex)) != -1)
{
boundaries.add(new EntitySubstitutionBoundaryData(entityName, entityPlaceholder, new Pair<Integer, Integer>(startIndex, startIndex + entityPlaceholderLength - 1)));
startIndex += entityPlaceholderLength;
}
}
/*
* if there are no boundaries, there is no need to do any
* substitutions
*/
if (boundaries.size() != 0)
{
/* Sort based on the start of the boundaries */
Collections.sort(boundaries, new EntitySubstitutionBoundaryDataBoundaryStartSort());
/* get the text content of the text node */
final String originalText = node.getTextContent();
/* the parent of this node holds only this text node. */
final Node parentNode = node.getParentNode();
/*
* loop through all the boundaries that define the position of
* the substitutions, and replace them with entity reference
* nodes.
*
* this involves adding a new sequence of text and entity
* reference nodes before the existing text node, and then
* removing the existing text node.
*/
for (int i = 0; i < boundaries.size(); ++i)
{
final EntitySubstitutionBoundaryData boundary = boundaries.get(i);
final EntitySubstitutionBoundaryData lastBoundary = i != 0 ? boundaries.get(i - 1) : null;
/* the entity node */
final Node entityNode = parentNode.getOwnerDocument().createEntityReference(boundary.getEntityName());
/* the first substitution where text proceeds it */
if (i == 0)
{
if (boundary.getBoundary().getFirst() != 0)
{
final Node textNode = parentNode.getOwnerDocument().createTextNode(originalText.substring(0, boundary.getBoundary().getFirst()));
parentNode.insertBefore(textNode, node);
}
/* append an entity node after the initial text node */
parentNode.insertBefore(entityNode, node);
}
else
{
/*
* there is a gap between the last boundary and this
* boundary
*/
if (lastBoundary.getBoundary().getSecond() + 1 != boundary.getBoundary().getFirst())
{
final Node textNode = parentNode.getOwnerDocument().createTextNode(originalText.substring(lastBoundary.getBoundary().getSecond() + 1, boundary.getBoundary().getFirst()));
parentNode.insertBefore(textNode, node);
}
}
/*