Example usage for org.w3c.dom Node getNextSibling

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

Introduction

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

Prototype

public Node getNextSibling();

Source Link

Document

The node immediately following this node.

Usage

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

/**
 * @param source parent of children//from w  w  w .j  av a  2 s .c o  m
 * @param dest receiver of children
 * @param ap User's authorization principal for determining if they can view a channel
 * @param visitedNodes A Set of nodes from the source tree that have been visited to get to this node, used to ensure a loop doesn't exist in the source tree.
 * @throws AuthorizationException
 */
private static void mergeChildren(Element source, Element dest, IAuthorizationPrincipal ap, Set visitedNodes)
        throws AuthorizationException {
    //Record this node in the visited nodes set. If add returns false a loop has been detected
    if (!visitedNodes.add(source)) {
        final String msg = "mergeChildren has encountered a loop in the source DOM. currentNode='" + source
                + "', currentDepth='" + visitedNodes.size() + "', visitedNodes='" + visitedNodes + "'";
        final IllegalStateException ise = new IllegalStateException(msg);
        LOG.error(msg, ise);

        printNodeToDebug(source, "Source");
        printNodeToDebug(dest, "Dest");

        throw ise;
    }

    Document destDoc = dest.getOwnerDocument();

    Node item = source.getFirstChild();
    while (item != null) {
        if (item instanceof Element) {

            Element child = (Element) item;
            Element newChild = null;

            if (null != child && mergeAllowed(child, ap)) {
                newChild = (Element) destDoc.importNode(child, false);
                dest.appendChild(newChild);
                String id = newChild.getAttribute(Constants.ATT_ID);
                if (id != null && !id.equals(""))
                    newChild.setIdAttribute(Constants.ATT_ID, true);
                mergeChildren(child, newChild, ap, visitedNodes);
            }
        }

        item = item.getNextSibling();
    }

    //Remove this node from the visited nodes set
    visitedNodes.remove(source);
}

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

/**
 * Get the parameter edits set if any stored in the root of the document or
 * create it if passed-in create flag is true.
 */// w w w .  j  ava 2  s. c  o m
private static Element getParmEditSet(Document plf, IPerson person, boolean create) throws PortalException {
    Node root = plf.getDocumentElement();
    Node child = root.getFirstChild();

    while (child != null) {
        if (child.getNodeName().equals(Constants.ELM_PARM_SET))
            return (Element) child;
        child = child.getNextSibling();
    }

    if (create == false)
        return null;

    String ID = null;

    try {
        ID = getDLS().getNextStructDirectiveId(person);
    } catch (Exception e) {
        throw new PortalException("Exception encountered while " + "generating new parameter edit set node "
                + "Id for userId=" + person.getID(), e);
    }
    Element parmSet = plf.createElement(Constants.ELM_PARM_SET);
    parmSet.setAttribute(Constants.ATT_TYPE, Constants.ELM_PARM_SET);
    parmSet.setAttribute(Constants.ATT_ID, ID);
    parmSet.setIdAttribute(Constants.ATT_ID, true);
    root.appendChild(parmSet);
    return parmSet;
}

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  o  m*/
 */
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 locates the position set element in the child list of the
   passed in plfParent or if not found it will create one automatically
   and return it if the passed in create flag is true.
*///from  w w w .  j  a v a2  s.  c o m
private static Element getPositionSet(Element plfParent, IPerson person, boolean create)
        throws PortalException {
    Node child = plfParent.getFirstChild();

    while (child != null) {
        if (child.getNodeName().equals(Constants.ELM_POSITION_SET))
            return (Element) child;
        child = child.getNextSibling();
    }
    if (create == false)
        return null;

    String ID = null;

    try {
        ID = getDLS().getNextStructDirectiveId(person);
    } catch (Exception e) {
        throw new PortalException("Exception encountered while " + "generating new position set node "
                + "Id for userId=" + person.getID(), e);
    }
    Document plf = plfParent.getOwnerDocument();
    Element positions = plf.createElement(Constants.ELM_POSITION_SET);
    positions.setAttribute(Constants.ATT_TYPE, Constants.ELM_POSITION_SET);
    positions.setAttribute(Constants.ATT_ID, ID);
    plfParent.appendChild(positions);
    return positions;
}

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

@Override
protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt)
        throws SQLException {
    if (node == null) { // No more
        return 0;
    }/*from   w w w .j a  v a2s.  c  o  m*/
    if (node.getNodeName().equals("parameter")) {
        //parameter, skip it and go on to the next node
        return this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    }
    if (!(node instanceof Element)) {
        return 0;
    }

    final Element structure = (Element) node;

    if (logger.isDebugEnabled()) {
        logger.debug("saveStructure XML content: {}", XmlUtilitiesImpl.toString(node));
    }

    // determine the struct_id for storing in the db. For incorporated nodes in
    // the plf their ID is a system-wide unique ID while their struct_id for
    // storing in the db is cached in a dlm:plfID attribute.
    int saveStructId = -1;
    final String plfID = structure.getAttribute(Constants.ATT_PLF_ID);

    if (!plfID.equals("")) {
        saveStructId = Integer.parseInt(plfID.substring(1));
    } else {
        final String id = structure.getAttribute("ID");
        saveStructId = Integer.parseInt(id.substring(1));
    }

    int nextStructId = 0;
    int childStructId = 0;
    int chanId = -1;
    IPortletDefinition portletDef = null;
    final boolean isChannel = node.getNodeName().equals("channel");

    if (isChannel) {
        chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
        portletDef = this.portletDefinitionRegistry.getPortletDefinition(String.valueOf(chanId));
        if (portletDef == null) {
            //Portlet doesn't exist any more, drop the layout node
            return 0;
        }
    }

    if (node.hasChildNodes()) {
        childStructId = this.saveStructure(node.getFirstChild(), structStmt, parmStmt);
    }
    nextStructId = this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    structStmt.clearParameters();
    structStmt.setInt(1, saveStructId);
    structStmt.setInt(2, nextStructId);
    structStmt.setInt(3, childStructId);

    final String externalId = structure.getAttribute("external_id");
    if (externalId != null && externalId.trim().length() > 0) {
        final Integer eID = new Integer(externalId);
        structStmt.setInt(4, eID.intValue());
    } else {
        structStmt.setNull(4, java.sql.Types.NUMERIC);

    }
    if (isChannel) {
        structStmt.setInt(5, chanId);
        structStmt.setNull(6, java.sql.Types.VARCHAR);
    } else {
        structStmt.setNull(5, java.sql.Types.NUMERIC);
        structStmt.setString(6, structure.getAttribute("name"));
    }
    final String structType = structure.getAttribute("type");
    structStmt.setString(7, structType);
    structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
    structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
    structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
    logger.debug(structStmt.toString());
    structStmt.executeUpdate();

    // code to persist extension attributes for dlm
    final NamedNodeMap attribs = node.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        final Node attrib = attribs.item(i);
        final String name = attrib.getNodeName();

        if (name.startsWith(Constants.NS) && !name.equals(Constants.ATT_PLF_ID)
                && !name.equals(Constants.ATT_FRAGMENT) && !name.equals(Constants.ATT_PRECEDENCE)) {
            // a cp extension attribute. Push into param table.
            parmStmt.clearParameters();
            parmStmt.setInt(1, saveStructId);
            parmStmt.setString(2, name);
            parmStmt.setString(3, attrib.getNodeValue());
            logger.debug(parmStmt.toString());
            parmStmt.executeUpdate();
        }
    }
    final NodeList parameters = node.getChildNodes();
    if (parameters != null && isChannel) {
        for (int i = 0; i < parameters.getLength(); i++) {
            if (parameters.item(i).getNodeName().equals("parameter")) {
                final Element parmElement = (Element) parameters.item(i);
                final NamedNodeMap nm = parmElement.getAttributes();
                final String parmName = nm.getNamedItem("name").getNodeValue();
                final String parmValue = nm.getNamedItem("value").getNodeValue();
                final Node override = nm.getNamedItem("override");

                // if no override specified then default to allowed
                if (override != null && !override.getNodeValue().equals("yes")) {
                    // can't override
                } else {
                    // override only for adhoc or if diff from chan def
                    final IPortletDefinitionParameter cp = portletDef.getParameter(parmName);
                    if (cp == null || !cp.getValue().equals(parmValue)) {
                        parmStmt.clearParameters();
                        parmStmt.setInt(1, saveStructId);
                        parmStmt.setString(2, parmName);
                        parmStmt.setString(3, parmValue);
                        logger.debug(parmStmt.toString());
                        parmStmt.executeUpdate();
                    }
                }
            }
        }
    }
    return saveStructId;
}

From source file:org.bibsonomy.importer.bookmark.file.FirefoxImporter.java

/**
 * Parses a given node and extracts all links and folders. Uppertags
 * contains all tags provided by nodes above the given node (folder).
 * Bookmarks is requiered because createBookmarks works recursively.
 * /*from   ww w .ja v a 2s  .  c om*/
 * @param Node
 *            folder
 * @param Vector
 *            <String> upperTags
 * @param LinkedList
 *            <Bookmark>bookmarks
 * @return
 */
private void createBookmarks(final Node folder, final Vector<String> upperTags, final User user,
        final String groupName) {
    // the post gets today's time
    final Date today = new Date();

    // every node requires his own tags
    Vector<String> tags;
    // if tags are provided by upper nodes these tags belong to this node
    // too
    if (upperTags != null) {
        tags = new Vector<String>(upperTags);
    }
    // if no tags are provided create a new vector
    else {
        tags = new Vector<String>();
    }
    // nodelist to parse all children of the given node
    NodeList children = folder.getChildNodes();
    // String to save a foldername if its name is given in a sibling of the
    // concerning DL
    String sepTag = "";

    for (int i = 0; i < children.getLength(); i++) {
        Node currentNode = children.item(i);
        // connect all upper tags with the currentNode
        Vector<String> myTags = new Vector<String>(tags);
        if (!"".equals(sepTag)) {
            myTags.add(sepTag);
        }

        // is currentNode a folder?
        if ("dd".equals(currentNode.getNodeName())) {
            NodeList secondGen = currentNode.getChildNodes();
            // only containing a name?
            // yes, keep tag
            if (secondGen.getLength() == 1 && "h3".equals(secondGen.item(0).getNodeName())) {
                sepTag = secondGen.item(0).getFirstChild().getNodeValue().replaceAll("->|<-|\\s", "_");
            } else if (secondGen.getLength() > 1) { // filtert dd-knoten,
                // die nur einen
                // p-knoten besitzen
                // else find all folders an theis names
                for (int j = 0; j < secondGen.getLength(); j++) {
                    Node son = secondGen.item(j);
                    if ("h3".equals(son.getNodeName())) {
                        // if sepTag != "" remove last added tag and reset
                        // sepTag
                        if (!"".equals(sepTag)) {
                            myTags.remove(sepTag);
                            sepTag = "";
                        }
                        // if upperTags != myTags, a parallel branch was
                        // parsed -> reset myTags
                        if (tags.size() != myTags.size()) {
                            myTags = tags;
                        }
                        // add a found tag
                        myTags.add(son.getFirstChild().getNodeValue().replaceAll("->|<-|\\s", "_"));
                    }
                    // all dl-nodes are new folders
                    if ("dl".equals(son.getNodeName())) {
                        // create bookmarks from new found node
                        createBookmarks(son, myTags, user, groupName);
                    }
                } // for(int j=...
            } // else if
        } // if ("dd".equals....
          // if its no folder.... is it a link?

        /*
         * sometimes the tidy parser decides that <dt></dt> has childnodes
         * ... need to check if the childnode of <dt> is an <a> to avoid
         * NullPointerExceptions!!!!
         */
        else if ("dt".equals(currentNode.getNodeName())
                && "a".equals(currentNode.getFirstChild().getNodeName())) {
            // it is a link
            // create bookmark-object

            // need to check if the <a>-Tag has a name (ChildNodes) i.e. <a
            // href="http://www.foo.bar"></a> causes a failure
            if (currentNode.getFirstChild().hasChildNodes() == true) {
                Post<Bookmark> bookmarkPost = new Post<Bookmark>();
                bookmarkPost.setResource(new Bookmark());
                bookmarkPost.getResource().setTitle(currentNode.getFirstChild().getFirstChild().getNodeValue());
                bookmarkPost.getResource().setUrl(
                        currentNode.getFirstChild().getAttributes().getNamedItem("href").getNodeValue());
                // add tags/relations to bookmark
                if (upperTags != null) {
                    // only 1 tag found -> add a tag
                    if (upperTags.size() == 1) {

                        // bookmark.setTags(upperTags.elementAt(0));
                        bookmarkPost.addTag(upperTags.elementAt(0));
                    } else {
                        // more tags found -> add relations
                        for (int tagCount = 0; tagCount < upperTags.size() - 1; tagCount++) {
                            String upper = upperTags.elementAt(tagCount);
                            String lower = upperTags.elementAt(tagCount + 1);
                            // bookmark.addTagRelation(lower, upper);
                            bookmarkPost.addTag(upper);
                            bookmarkPost.addTag(lower);

                        }
                    }
                } else {
                    /*
                     * link found in "root-folder" -> no folder hierarchy
                     * found
                     * 
                     * check for "TAGS" attribute (common in del.icio.us
                     * export)
                     */
                    final Node tagNode = currentNode.getFirstChild().getAttributes().getNamedItem("tags");
                    if (tagNode != null) {
                        /*
                         * del.icio.us export tags are comma-separated
                         */
                        final StringTokenizer token = new StringTokenizer(tagNode.getNodeValue(), ",");
                        while (token.hasMoreTokens()) {
                            bookmarkPost.addTag(token.nextToken());
                        }
                    } else {
                        // really no tags found -> set imported tag
                        bookmarkPost.setTags(Collections.singleton(TagUtils.getEmptyTag()));
                    }
                }
                bookmarkPost.setDate(today);
                bookmarkPost.setUser(user);
                bookmarkPost.addGroup(groupName);

                // descriptions are saved in a sibling of of a node
                // containing a link
                if (currentNode.getNextSibling() != null
                        && "dd".equals(currentNode.getNextSibling().getNodeName())) {
                    // bookmark.setExtended(currentNode.getNextSibling().getFirstChild().getNodeValue());
                    bookmarkPost.setDescription(currentNode.getNextSibling().getFirstChild().getNodeValue());
                }
                posts.add(bookmarkPost);
            }
        }
    }
}

From source file:org.carewebframework.shell.layout.UILayout.java

/**
 * Sets the current node to the specified value. If the value is not an element node, sets the
 * current node to the first sibling node that is an element.
 * /*from w ww  . j  a v  a  2  s .  c  o  m*/
 * @param node Node to become current node.
 * @return True if the current node was successfully set.
 */
private boolean setCurrentNode(Node node) {
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            currentNode = node;
            return true;
        }
        node = node.getNextSibling();
    }

    return false;
}

From source file:org.dita.dost.AbstractIntegrationTest.java

private void removeWorkdirProcessingInstruction(final Element e) {
    Node n = e.getFirstChild();
    while (n != null) {
        final Node next = n.getNextSibling();
        if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE && (n.getNodeName().equals(PI_WORKDIR_TARGET)
                || n.getNodeName().equals(PI_WORKDIR_TARGET_URI))) {
            e.removeChild(n);/*from www .j  av  a  2  s  . c  o  m*/
        }
        n = next;
    }
}

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

private void addStubElements() {
    stub = rootTopicref.getOwnerDocument().createElement(ELEMENT_STUB);
    siblingStub = rootTopicref.getOwnerDocument().createElement(ELEMENT_STUB);
    if (rootTopicref.hasChildNodes()) {
        final NodeList list = rootTopicref.getElementsByTagName(MAP_TOPICMETA.localName);
        if (list.getLength() > 0) {
            final Node node = list.item(0);
            final Node nextSibling = node.getNextSibling();
            // no sibling so node is the last child
            if (nextSibling == null) {
                node.getParentNode().appendChild(stub);
            } else {
                // has sibling node
                node.getParentNode().insertBefore(stub, nextSibling);
            }/*from  w  ww . j ava  2s.  c  om*/
        } else {
            // no topicmeta tag.
            rootTopicref.insertBefore(stub, rootTopicref.getFirstChild());
        }
    } else {
        rootTopicref.appendChild(stub);
    }
}

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

@Test
public void testWrite() throws DITAOTException, ParserConfigurationException, SAXException, IOException {
    /*//from  w w w. j  av a  2s. 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));
                }
            }
        }

    }
}