### Question:
ComponentTreeRewriter { public Node rewrite(Node root) throws RewriteException, RepositoryException { String rootPath = root.getPath(); logger.debug("Rewriting component's content tree rooted at {}", rootPath); long tick = System.currentTimeMillis(); Session session = root.getSession(); boolean success = false; Node startNode = root; try { Node parent = root.getParent(); boolean ordered = parent.getPrimaryNodeType().hasOrderableChildNodes(); NodeIterator siblings = parent.getNodes(); while (siblings.hasNext()) { Node node = siblings.nextNode(); if (startNode.getPath().equals(node.getPath())) { for (ComponentRewriteRule rule : rules) { if (rule.matches(node)) { logger.debug("Rule {} matched subtree rooted at {}", rule, node.getPath()); node = rule.applyTo(node, new HashSet<>()); startNode = node; break; } } } if (ordered) { parent.orderBefore(node.getName(), null); } } success = true; } finally { if (!success) { try { session.refresh(false); } catch (RepositoryException e) { logger.warn("Could not revert changes", e); } } } session.save(); long tack = System.currentTimeMillis(); logger.debug("Rewrote component tree rooted at {} in {} ms", rootPath, tack - tick); return startNode; } ComponentTreeRewriter(List<ComponentRewriteRule> rules); Node rewrite(Node root);  }### Answer:
@Test public void testRewriteMaintainsOrder() throws Exception { Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/level1/mapProperties").adaptTo(Node.class); List<ComponentRewriteRule> rules = componentRewriteRuleService.getRules(context.resourceResolver()); ComponentTreeRewriter rewriter = new ComponentTreeRewriter(rules); Node rewrittenNode = rewriter.rewrite(rootNode); assertEquals("map-property-3", rewrittenNode.getProperty("map-property-nested").getValue().getString()); Node level1 = context.resourceResolver().getResource(ROOTS_PATH + "/level1").adaptTo(Node.class); NodeIterator nit = level1.getNodes(); assertEquals("simple", nit.nextNode().getName()); assertEquals("mapProperties", nit.nextNode().getName()); assertEquals("rewriteProperties", nit.nextNode().getName()); assertEquals("rewriteMapChildren", nit.nextNode().getName()); }