Example usage for org.w3c.dom Element getNextSibling

List of usage examples for org.w3c.dom Element getNextSibling

Introduction

In this page you can find the example usage for org.w3c.dom Element getNextSibling.

Prototype

public Node getNextSibling();

Source Link

Document

The node immediately following this node.

Usage

From source file:org.apereo.portal.layout.dlm.PLFIntegrator.java

private static void applyChildChanges(Element plfParent, Element ilfParent, IntegrationResult result,
        NodeInfoTracker tracker) throws PortalException {

    Element positions = null;//  w  w w  .  j av a2 s.c  om
    Element node = (Element) plfParent.getFirstChild();

    while (node != null) {
        Element nextNode = (Element) node.getNextSibling();

        if (node.getNodeName().equals("folder"))
            mergeFolder(node, plfParent, ilfParent, result, tracker);
        else if (node.getNodeName().equals(Constants.ELM_POSITION_SET))
            positions = node;
        else if (node.getNodeName().equals("channel"))
            mergeChannel(node, plfParent, ilfParent, result, tracker);
        node = nextNode;
    }

    if (positions != null) {
        IntegrationResult posResult = new IntegrationResult();
        if (LOG.isInfoEnabled())
            LOG.info("applying positions");
        PositionManager.applyPositions(ilfParent, positions, posResult, tracker);
        if (!posResult.isChangedILF()) {
            if (LOG.isInfoEnabled())
                LOG.info("removing positionSet");
            plfParent.removeChild(positions);
            result.setChangedPLF(true);
        } else {
            result.setChangedILF(true);
            if (posResult.isChangedPLF())
                result.setChangedPLF(true);
        }
    }
}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
   This method trims down the position set to the position directives on
   the node info elements still having a position directive. Any directives
   that violated restrictions were removed from the node info objects so
   the position set should be made to match the order of those still
   having one./*from   w w  w .  j a  v a  2  s  .  c  om*/
 */
static void adjustPositionSet(List<NodeInfo> order, Element positionSet, IntegrationResult result) {
    Node nodeToMatch = positionSet.getFirstChild();
    Element nodeToInsertBefore = positionSet.getOwnerDocument().createElement("INSERT_POINT");
    positionSet.insertBefore(nodeToInsertBefore, nodeToMatch);

    for (Iterator<NodeInfo> iter = order.iterator(); iter.hasNext();) {
        NodeInfo ni = iter.next();

        if (ni.getPositionDirective() != null) {
            // found one check it against the current one in the position
            // set to see if it is different. If so then indicate that
            // something (the position set) has changed in the plf
            if (ni.getPositionDirective() != nodeToMatch)
                result.setChangedPLF(true);
            ;

            // now bump the insertion point forward prior to
            // moving on to the next position node to be evaluated
            if (nodeToMatch != null)
                nodeToMatch = nodeToMatch.getNextSibling();

            // now insert it prior to insertion point
            positionSet.insertBefore(ni.getPositionDirective(), nodeToInsertBefore);
        }
    }

    // now for any left over after the insert point remove them.

    while (nodeToInsertBefore.getNextSibling() != null)
        positionSet.removeChild(nodeToInsertBefore.getNextSibling());

    // now remove the insertion point
    positionSet.removeChild(nodeToInsertBefore);
}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
   This method compares the children by id in the order list with
   the order in the compViewParent's ui visible children and returns true
   if the ordering differs indicating that the positioning if needed.
 *//*from  www .j a va  2 s  .c  o  m*/
static boolean hasAffectOnCVP(List<NodeInfo> order, Element compViewParent) {
    if (order.size() == 0)
        return false;

    int idx = 0;
    Element child = (Element) compViewParent.getFirstChild();
    NodeInfo ni = order.get(idx);

    if (child == null && ni != null) // most likely nodes to be pulled in
        return true;

    while (child != null) {
        if (child.getAttribute("hidden").equals("false")
                && (!child.getAttribute("chanID").equals("") || child.getAttribute("type").equals("regular"))) {
            if (ni.getId().equals(child.getAttribute(Constants.ATT_ID))) {
                if (idx >= order.size() - 1) // at end of order list
                    return false;

                ni = order.get(++idx);
            } else // if not equal then return true
                return true;
        }
        child = (Element) child.getNextSibling();
    }
    if (idx < order.size())
        return true; // represents nodes to be pulled in
    return false;
}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
 * Return true if the passed in node or any downstream (higher index)
 * siblings <strong>relative to its destination location</strong> have
 * moveAllowed="false"./* ww w.  j  a  va2  s. com*/
 */
private static boolean isNotReparentable(NodeInfo ni, Element compViewParent, Element positionSet) {

    // This one is easy -- can't re-parent a node with dlm:moveAllowed=false
    if (ni.getNode().getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {
        return true;
    }

    try {
        /*
         *  Annoying to do in Java, but we need to find our own placeholder
         *  element in the positionSet
         */
        final XPathFactory xpathFactory = XPathFactory.newInstance();
        final XPath xpath = xpathFactory.newXPath();
        final String findPlaceholderXpath = ".//*[local-name()='position' and @name='" + ni.getId() + "']";
        final XPathExpression findPlaceholder = xpath.compile(findPlaceholderXpath);
        final NodeList findPlaceholderList = (NodeList) findPlaceholder.evaluate(positionSet,
                XPathConstants.NODESET);
        switch (findPlaceholderList.getLength()) {
        case 0:
            LOG.warn("Node not found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet="
                    + XmlUtilitiesImpl.toString(positionSet));
            return true;
        case 1:
            // This is healthy
            break;
        default:
            LOG.warn("More than one node found for XPathExpression=\"" + findPlaceholderXpath
                    + "\" in positionSet=" + XmlUtilitiesImpl.toString(positionSet));
            return true;
        }
        final Element placeholder = (Element) findPlaceholderList.item(0); // At last

        for (Element nextPlaceholder = (Element) placeholder.getNextSibling(); // Start with the next dlm:position element after placeholder
                nextPlaceholder != null; // As long as we have a placeholder to look at
                nextPlaceholder = (Element) nextPlaceholder.getNextSibling()) { // Advance to the next placeholder

            if (LOG.isDebugEnabled()) {
                LOG.debug("Considering whether node ''" + ni.getId()
                        + "' is Reparentable;  subsequent sibling is:  "
                        + nextPlaceholder.getAttribute("name"));
            }

            /*
             * Next task:  we have to find the non-placeholder representation of
             * the nextSiblingPlaceholder within the compViewParent
             */
            final String unmaskPlaceholderXpath = ".//*[@ID='" + nextPlaceholder.getAttribute("name") + "']";
            final XPathExpression unmaskPlaceholder = xpath.compile(unmaskPlaceholderXpath);
            final NodeList unmaskPlaceholderList = (NodeList) unmaskPlaceholder.evaluate(compViewParent,
                    XPathConstants.NODESET);
            switch (unmaskPlaceholderList.getLength()) {
            case 0:
                // Not a problem;  the nextSiblingPlaceholder also refers
                // to a node that has been moved to this context (afaik)
                continue;
            case 1:
                final Element nextSibling = (Element) unmaskPlaceholderList.item(0);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Considering whether node ''" + ni.getId()
                            + "' is Reparentable;  subsequent sibling '" + nextSibling.getAttribute("ID")
                            + "' has dlm:moveAllowed="
                            + !nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false"));
                }

                // Need to perform some checks...
                if (nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {

                    /*
                     *  The following check is a bit strange;  it seems to verify
                     *  that the current NodeInfo and the nextSibling come from the
                     *  same fragment.  If they don't, the re-parenting is allowable.
                     *  I believe this check could only be unsatisfied in the case
                     *  of tabs.
                     */
                    Precedence p = Precedence.newInstance(nextSibling.getAttribute(Constants.ATT_FRAGMENT));
                    if (ni.getPrecedence().isEqualTo(p)) {
                        return true;
                    }
                }
                break;
            default:
                LOG.warn("More than one node found for XPathExpression=\"" + unmaskPlaceholderXpath
                        + "\" in compViewParent");
                return true;
            }
        }
    } catch (XPathExpressionException xpe) {
        throw new RuntimeException("Failed to evaluate XPATH", xpe);
    }

    return false; // Re-parenting is "not disallowed" (double-negative less readable)

}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
   This method assembles in the passed in order object a list of NodeInfo
   objects ordered first by those specified in the position set and whose
   nodes still exist in the composite view and then by any remaining
   children in the compViewParent.//from   ww  w .  j  a  v  a 2 s .  c o m
 */
static void applyOrdering(List<NodeInfo> order, Element compViewParent, Element positionSet,
        NodeInfoTracker tracker) {

    // first pull out all visible channel or visible folder children and
    // put their id's in a list of available children and record their
    // relative order in the CVP.

    final Map<String, NodeInfo> available = new LinkedHashMap<String, NodeInfo>();

    Element child = (Element) compViewParent.getFirstChild();
    Element next = null;
    int indexInCVP = 0;

    while (child != null) {
        next = (Element) child.getNextSibling();

        if (child.getAttribute("hidden").equals("false")
                && (!child.getAttribute("chanID").equals("") || child.getAttribute("type").equals("regular"))) {
            final NodeInfo nodeInfo = new NodeInfo(child, indexInCVP++);

            tracker.track(nodeInfo, order, compViewParent, positionSet);

            final NodeInfo prevNode = available.put(nodeInfo.getId(), nodeInfo);
            if (prevNode != null) {
                throw new IllegalStateException("Infinite loop detected in layout. Triggered by "
                        + nodeInfo.getId() + " with already visited node ids: " + available.keySet());
            }
        }
        child = next;
    }

    // now fill the order list using id's from the position set if nodes
    // having those ids exist in the composite view. Otherwise discard
    // that position directive. As they are added to the list remove them
    // from the available nodes in the parent.

    Document CV = compViewParent.getOwnerDocument();
    Element directive = (Element) positionSet.getFirstChild();

    while (directive != null) {
        next = (Element) directive.getNextSibling();

        // id of child to move is in the name attrib on the position nodes
        String id = directive.getAttribute("name");
        child = CV.getElementById(id);

        if (child != null) {
            // look for the NodeInfo for this node in the available
            // nodes and if found use that one. Otherwise use a new that
            // does not include an index in the CVP parent. In either case
            // indicate the position directive responsible for placing this
            // NodeInfo object in the list.

            final String childId = child.getAttribute(Constants.ATT_ID);
            NodeInfo ni = available.remove(childId);
            if (ni == null) {
                ni = new NodeInfo(child);
                tracker.track(ni, order, compViewParent, positionSet);
            }

            ni.setPositionDirective(directive);
            order.add(ni);
        }
        directive = next;
    }

    // now append any remaining ids from the available list maintaining
    // the order that they have there.

    order.addAll(available.values());

}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
   This method updates the positions recorded in a position set to reflect
   the ids of the nodes in the composite view of the layout. Any position
   nodes already in existence are reused to reduce database interaction
   needed to generate a new ID attribute. If any are left over after
   updating those position elements are removed. If no position set existed
   a new one is created for the parent. If no ILF nodes are found in the
   parent node then the position set as a whole is reclaimed.
*/// w w w  .  j a  v a2  s .com
public static void updatePositionSet(Element compViewParent, Element plfParent, IPerson person)
        throws PortalException {
    if (LOG.isDebugEnabled())
        LOG.debug("Updating Position Set");

    if (compViewParent.getChildNodes().getLength() == 0) {
        // no nodes to position. if set exists reclaim the space.
        if (LOG.isDebugEnabled())
            LOG.debug("No Nodes to position");
        Element positions = getPositionSet(plfParent, person, false);
        if (positions != null)
            plfParent.removeChild(positions);
        return;
    }
    Element posSet = (Element) getPositionSet(plfParent, person, true);
    Element position = (Element) posSet.getFirstChild();
    Element viewNode = (Element) compViewParent.getFirstChild();
    boolean ilfNodesFound = false;

    while (viewNode != null) {
        String ID = viewNode.getAttribute(Constants.ATT_ID);
        String channelId = viewNode.getAttribute(Constants.ATT_CHANNEL_ID);
        String type = viewNode.getAttribute(Constants.ATT_TYPE);
        String hidden = viewNode.getAttribute(Constants.ATT_HIDDEN);

        if (ID.startsWith(Constants.FRAGMENT_ID_USER_PREFIX))
            ilfNodesFound = true;

        if (!channelId.equals("") || // its a channel node or
                (type.equals("regular") && // a regular, visible folder
                        hidden.equals("false"))) {
            if (position != null)
                position.setAttribute(Constants.ATT_NAME, ID);
            else
                position = createAndAppendPosition(ID, posSet, person);
            position = (Element) position.getNextSibling();
        }
        viewNode = (Element) viewNode.getNextSibling();
    }

    if (ilfNodesFound == false) // only plf nodes, no pos set needed
        plfParent.removeChild(posSet);
    else {
        // reclaim any leftover positions
        while (position != null) {
            Element nextPos = (Element) position.getNextSibling();
            posSet.removeChild(position);
            position = nextPos;
        }
    }
}

From source file:org.dhatim.templating.AbstractTemplateProcessor.java

private void _processTemplateAction(Element element, Node node, Action action,
        ExecutionContext executionContext) {
    Node parent = element.getParentNode();

    // Can't insert before or after the root element...
    if (parent instanceof Document && (action == Action.INSERT_BEFORE || action == Action.INSERT_AFTER)) {
        logger.debug("Insert before/after root element not allowed.  Consider using the replace action!!");
        return;//from w w w .  j  a  v a2  s  .co  m
    }

    String outputStreamResourceName = getOutputStreamResource();
    if (outputStreamResourceName != null) {
        Writer writer = AbstractOutputStreamResource.getOutputWriter(outputStreamResourceName,
                executionContext);
        String text = extractTextContent(node, executionContext);
        try {
            writer.write(text);
        } catch (IOException e) {
            throw new SmooksException(
                    "Failed to write to output stream resource '" + outputStreamResourceName + "'.", e);
        }
    } else {
        if (action == Action.ADDTO) {
            element.appendChild(node);
        } else if (action == Action.INSERT_BEFORE) {
            DomUtils.insertBefore(node, element);
        } else if (action == Action.INSERT_AFTER) {
            Node nextSibling = element.getNextSibling();

            if (nextSibling == null) {
                // "element" is the last child of "parent" so just add to "parent".
                parent.appendChild(node);
            } else {
                // insert before the "nextSibling" - Node doesn't have an "insertAfter" operation!
                DomUtils.insertBefore(node, nextSibling);
            }
        } else if (action == Action.BIND_TO) {
            String text = extractTextContent(node, executionContext);

            executionContext.getBeanContext().addBean(bindBeanId, text, new Fragment(element));
        } else if (action == Action.REPLACE) {
            // Don't perform any "replace" actions here!
        }
    }
}

From source file:org.dita.dost.module.BranchFilterModule.java

/**
 * Duplicate branches so that each {@code ditavalref} will in a separate branch.
 *///  w  w w .  jav  a 2s .  co m
void splitBranches(final Element elem, final Branch filter) {
    final List<Element> ditavalRefs = getChildElements(elem, DITAVAREF_D_DITAVALREF);
    if (ditavalRefs.size() > 0) {
        // remove ditavalrefs
        for (final Element branch : ditavalRefs) {
            elem.removeChild(branch);
        }
        // create additional branches after current element
        final List<Element> branches = new ArrayList<>(ditavalRefs.size());
        branches.add(elem);
        final Node next = elem.getNextSibling();
        for (int i = 1; i < ditavalRefs.size(); i++) {
            final Element clone = (Element) elem.cloneNode(true);
            if (next != null) {
                elem.getParentNode().insertBefore(clone, next);
            } else {
                elem.getParentNode().appendChild(clone);
            }
            branches.add(clone);
        }
        // insert ditavalrefs
        for (int i = 0; i < branches.size(); i++) {
            final Element branch = branches.get(i);
            final Element ditavalref = ditavalRefs.get(i);
            branch.appendChild(ditavalref);
            final Branch currentFilter = filter.merge(ditavalref);
            processAttributes(branch, currentFilter);
            final Branch childFilter = new Branch(currentFilter.resourcePrefix, currentFilter.resourceSuffix,
                    Optional.empty(), Optional.empty());
            // process children of all branches
            for (final Element child : getChildElements(branch, MAP_TOPICREF)) {
                if (DITAVAREF_D_DITAVALREF.matches(child)) {
                    continue;
                }
                splitBranches(child, childFilter);
            }
        }
    } else {
        processAttributes(elem, filter);
        for (final Element child : getChildElements(elem, MAP_TOPICREF)) {
            splitBranches(child, filter);
        }
    }
}

From source file:org.dita.dost.writer.TestConrefPushParser.java

@Test
public void testWrite() throws DITAOTException, ParserConfigurationException, SAXException, IOException {
    /*/* w  ww . ja va2 s . c  o m*/
     * the part of content of conrefpush_stub2.xml is
     * <ol>
     *    <li id="A">A</li>
     *    <li id="B">B</li>
     *    <li id="C">C</li>
     * </ol>
     * 
     * the part of content of conrefpush_stup.xml is
     *  <steps>
     *     <step conaction="pushbefore"><cmd>before</cmd></step>
     *   <step conref="conrefpush_stub2.xml#X/A" conaction="mark"/>
     *   <step conref="conrefpush_stub2.xml#X/B" conaction="mark"/>
     *    <step conaction="pushafter"><cmd>after</cmd></step>
     *    <step conref="conrefpush_stub2.xml#X/C" conaction="pushreplace"><cmd>replace</cmd></step>
     *   </steps>
     *
     * after conrefpush the part of conrefpush_stub2.xml should be like this
     * <ol class="- topic/ol ">
     *  <li class="- topic/li task/step ">
     *     <ph class="- topic/ph task/cmd ">
     *     before
     *     </ph>
     *  </li>
     *  <li id="A" class="- topic/li ">A</li>
     *   <li id="B" class="- topic/li ">B</li>
     *   <li class="- topic/li task/step ">
     *      <ph class="- topic/ph task/cmd ">
     *      after
     *      </ph>
     *   </li>
     *   <li class="- topic/li task/step ">
     *      <ph class="- topic/ph task/cmd ">
     *      replace
     *      </ph>
     *   </li>
     * </ol>
     */
    final ConrefPushParser parser = new ConrefPushParser();
    parser.setLogger(new TestUtils.TestLogger());
    parser.setJob(new Job(tempDir));
    final ConrefPushReader reader = new ConrefPushReader();

    reader.read(inputFile.getAbsoluteFile());
    final Map<File, Hashtable<MoveKey, DocumentFragment>> pushSet = reader.getPushMap();
    final Iterator<Map.Entry<File, Hashtable<MoveKey, DocumentFragment>>> iter = pushSet.entrySet().iterator();
    if (iter.hasNext()) {
        final Map.Entry<File, Hashtable<MoveKey, DocumentFragment>> entry = iter.next();
        // initialize the parsed file
        copyFile(new File(srcDir, "conrefpush_stub2_backup.xml"), entry.getKey());
        //            final Content content = new ContentImpl();
        //            content.setValue(entry.getValue());
        //            parser.setContent(content);
        parser.setMoveTable(entry.getValue());
        parser.write(entry.getKey());
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(entry.getKey());
        final Element elem = document.getDocumentElement();
        NodeList nodeList = elem.getChildNodes();
        // according to the structure, it comes to the <li> after 2 iterations.
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < nodeList.getLength(); j++) {
                if (nodeList.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    nodeList = nodeList.item(j).getChildNodes();
                    break;
                }
            }
        }
        Element element;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                element = (Element) node;
                if (element.getAttributes().getNamedItem("id") != null
                        && element.getAttributes().getNamedItem("id").getNodeValue().equals("A")) {
                    // get node of before
                    node = element.getPreviousSibling();
                    while (node.getNodeType() != Node.ELEMENT_NODE) {
                        node = node.getPreviousSibling();
                    }
                    assertEquals(
                            "<li class=\"- topic/li task/step \"><ph class=\"- topic/ph task/cmd \">before</ph></li>",
                            nodeToString((Element) node));
                } else if (element.getAttributes().getNamedItem("id") != null
                        && element.getAttributes().getNamedItem("id").getNodeValue().equals("B")) {
                    // get node of after
                    node = element.getNextSibling();
                    while (node.getNodeType() != Node.ELEMENT_NODE) {
                        node = node.getNextSibling();
                    }
                    assertEquals(
                            "<li class=\"- topic/li task/step \"><ph class=\"- topic/ph task/cmd \">after</ph></li>",
                            nodeToString((Element) node));

                    // get node of replacement
                    node = node.getNextSibling();
                    while (node.getNodeType() != Node.ELEMENT_NODE) {
                        node = node.getNextSibling();
                    }
                    assertEquals(
                            "<li class=\"- topic/li task/step \" id=\"C\"><ph class=\"- topic/ph task/cmd \">replace</ph></li>",
                            nodeToString((Element) node));
                }
            }
        }

    }
}

From source file:org.etudes.tool.melete.ViewSectionsPage.java

private Node getNextNode(Element secElement) {
    if (secElement.hasChildNodes()) {
        return secElement.getFirstChild();
    } else {/*from w  ww .  j  a va2s .c o m*/
        if (secElement.getNextSibling() != null) {
            return secElement.getNextSibling();
        } else {
            if (secElement.getParentNode() != null) {
                if (secElement.getParentNode().getNodeName().equals("module")) {
                    return null;
                } else {
                    return getParentsNextSibling(secElement);
                }
            } else {
                return null;
            }
        }
    }
}