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.structr.web.entity.dom.DOMNode.java

@Override
public Node appendChild(final Node newChild) throws DOMException {

    checkWriteAccess();/* www . j  a v  a 2  s.  com*/
    checkSameDocument(newChild);
    checkHierarchy(newChild);

    try {

        if (newChild instanceof DocumentFragment) {

            // When inserting document fragments, we must take
            // care of the special case that the nodes already
            // have a NEXT_LIST_ENTRY relationship coming from
            // the document fragment, so we must first remove
            // the node from the document fragment and then
            // add it to the new parent.
            // replace indirectly using insertBefore and remove
            final DocumentFragment fragment = (DocumentFragment) newChild;
            Node currentChild = fragment.getFirstChild();

            while (currentChild != null) {

                // save next child in fragment list for later use
                final Node savedNextChild = currentChild.getNextSibling();

                // remove child from document fragment
                fragment.removeChild(currentChild);

                // append child to new parent
                appendChild(currentChild);

                // next
                currentChild = savedNextChild;
            }

        } else {

            final Node _parent = newChild.getParentNode();

            if (_parent != null && _parent instanceof DOMNode) {
                _parent.removeChild(newChild);
            }

            treeAppendChild((DOMNode) newChild);

            // allow parent to set properties in new child
            handleNewChild(newChild);
        }

    } catch (FrameworkException fex) {

        throw new DOMException(DOMException.INVALID_STATE_ERR, fex.toString());
    }

    return newChild;
}

From source file:org.structr.web.entity.dom.Page.java

private Node importNode(final Node node, final boolean deep, final boolean removeParentFromSourceNode)
        throws DOMException {

    if (node instanceof DOMNode) {

        final DOMNode domNode = (DOMNode) node;

        // step 1: use type-specific import impl.
        Node importedNode = domNode.doImport(Page.this);

        // step 2: do recursive import?
        if (deep && domNode.hasChildNodes()) {

            // FIXME: is it really a good idea to do the
            // recursion inside of a transaction?
            Node child = domNode.getFirstChild();

            while (child != null) {

                // do not remove parent for child nodes
                importNode(child, deep, false);
                child = child.getNextSibling();

                logger.log(Level.INFO, "sibling is {0}", child);
            }/*w ww  . j a  va 2  s  .  co m*/

        }

        // step 3: remove node from its current parent
        // (Note that this step needs to be done last in
        // (order for the child to be able to find its
        // siblings.)
        if (removeParentFromSourceNode) {

            // only do this for the actual source node, do not remove
            // child nodes from its parents
            Node _parent = domNode.getParentNode();
            if (_parent != null) {
                _parent.removeChild(domNode);
            }
        }

        return importedNode;

    }

    return null;
}

From source file:org.structr.web.entity.dom.Page.java

private Node adoptNode(final Node node, final boolean removeParentFromSourceNode) throws DOMException {

    if (node instanceof DOMNode) {

        final DOMNode domNode = (DOMNode) node;

        // step 2: do recursive import?
        if (domNode.hasChildNodes()) {

            Node child = domNode.getFirstChild();
            while (child != null) {

                // do not remove parent for child nodes
                adoptNode(child, false);
                child = child.getNextSibling();
            }/*www  . j  a va 2 s  .  c  o  m*/

        }

        // step 3: remove node from its current parent
        // (Note that this step needs to be done last in
        // (order for the child to be able to find its
        // siblings.)
        if (removeParentFromSourceNode) {

            // only do this for the actual source node, do not remove
            // child nodes from its parents
            Node _parent = domNode.getParentNode();
            if (_parent != null) {
                _parent.removeChild(domNode);
            }
        }

        // step 1: use type-specific adopt impl.
        Node adoptedNode = domNode.doAdopt(Page.this);

        return adoptedNode;

    }

    return null;
}

From source file:org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument.java

/**
 * Function to set/replace/update an object (String / Element) to matching the xPath provided. (In case new element
 * is added, this api will clone it and merge the new node to the target location pointed by xPath and return the new cloned node)
 *
 * @param xPathStr xPath to the location object need to set
 * @param obj      String or Node//from w w w .  ja  v a 2 s.c o m
 * @return returns the node get updated when the set object is String, or returns newly added Node in case object is Element
 * @throws XPathExpressionException If expression cannot be evaluated
 * @throws BPMNXmlException         is thrown due to : Provided XPath and object does not match, provided object is not a Node or String
 *                                  result is NodeList, not a Text node or Element
 */
public Node set(String xPathStr, Object obj) throws XPathExpressionException, BPMNXmlException {

    NodeList evalResult = (NodeList) Utils.evaluateXPath(this.doc, xPathStr, XPathConstants.NODESET);
    if (evalResult.getLength() == 1) {
        Node targetNode = evalResult.item(0);

        if (obj instanceof String && targetNode instanceof Text) { //if string is provided, assume that user
            //need to replace the node value
            targetNode.setNodeValue((String) obj);
            //return updated Text Node
            return targetNode;

        } else if ((obj instanceof Integer || obj instanceof Byte || obj instanceof Character
                || obj instanceof Short || obj instanceof Long || obj instanceof Float || obj instanceof Double
                || obj instanceof Boolean) && targetNode instanceof Text) {
            //need to replace the node value
            targetNode.setNodeValue(obj.toString());
            //return updated Text Node
            return targetNode;

        } else if (obj instanceof Element && targetNode instanceof Element
                && targetNode.getParentNode() != null) { //if the user provides Node object,
            // assume that need to replace the target node
            Node targetParent = targetNode.getParentNode();
            Node nextSibling = targetNode.getNextSibling();
            //remove the target node
            targetParent.removeChild(targetNode);
            //add new node
            Node newNode = doc.importNode((Node) obj, true);

            if (nextSibling != null) {
                //If next sibling exists we have to put the new node before it
                targetParent.insertBefore(newNode, nextSibling);
            } else {
                targetParent.appendChild(newNode);
            }
            //return new node
            return newNode;

        } else { //provided XPath and object to set does not match
            throw new BPMNXmlException("Provided XPath and provided object does not match");
        }

    } else if (evalResult.getLength() > 0) {

        throw new BPMNXmlException(
                "Error in provided xPath. Evaluation result is NodeList, not a Text node or Element");

    } else {
        throw new BPMNXmlException("Error in provided xPath. Evaluation result is not a Text node or Element");
    }

}

From source file:org.wso2.developerstudio.eclipse.esb.impl.ModelObjectImpl.java

protected Element addComments(Element self) throws Exception {
    if (comment != null) {
        for (int i = 0; i < comment.size(); ++i) {
            Node tempNode = self.getFirstChild();
            for (int j = 0; (tempNode != null) && (j < comment.get(i).getPosition()); ++j) {
                tempNode = tempNode.getNextSibling();
            }//from ww  w.  j  av  a 2 s. c  o  m
            self.insertBefore(self.getOwnerDocument().createComment(comment.get(i).getValue()), tempNode);
        }
    }
    return null;
}

From source file:org.xwiki.officeimporter.internal.filter.ListFilter.java

/**
 * {@inheritDoc}//from   ww w.  jav  a 2 s  . c o  m
 */
public void filter(Document document, Map<String, String> cleaningParams) {
    List<Element> listItems = filterDescendants(document.getDocumentElement(), new String[] { TAG_LI });
    for (Element listItem : listItems) {
        Node nextChild = listItem.getFirstChild();
        while (nextChild != null) {
            if (nextChild.getNodeType() == Node.TEXT_NODE) {
                String trimmed = StringUtils.stripStart(nextChild.getTextContent(), WHITE_SPACE_CHARS);
                nextChild.setTextContent(trimmed);
                if (trimmed.equals("")) {
                    nextChild = nextChild.getNextSibling();
                    continue;
                }
            } else if (nextChild.getNodeName().equals(TAG_P)) {
                replaceWithChildren((Element) nextChild);
            }
            break;
        }
    }
}

From source file:org.xwiki.validator.DutchWebGuidelinesValidator.java

/**
 * Use the p (paragraph) element to indicate paragraphs. Do not use the br (linebreak) element to separate
 * paragraphs./*from www .  ja va  2s . co m*/
 */
public void validateRpd3s4() {
    for (Node br : getElements(ELEM_BR)) {

        Node currentNode = br.getNextSibling();

        while (currentNode != null && currentNode.getNodeType() == Node.TEXT_NODE
                && StringUtils.isBlank(currentNode.getTextContent())) {
            // Ignore white spaces between <br/>.
            currentNode = currentNode.getNextSibling();
        }

        if (currentNode != null) {
            assertFalse(Type.ERROR, "rpd3s4.linebreaks", currentNode.getNodeName().equals(ELEM_BR));
        }
    }
}

From source file:org.xwiki.validator.DutchWebGuidelinesValidator.java

/**
 * Use ol (ordered list) and ul (unordered list) elements to indicate lists.
 *//*from   ww  w.j  a v a  2  s .c o m*/
public void validateRpd3s13() {
    for (Node br : getElements(ELEM_BR)) {
        Node previousNode = null;
        String regex = "^\\s*(\\*|-|[0-9]\\.).*";

        for (Node currentNode : new NodeListIterable(br.getParentNode().getChildNodes())) {
            Node nextNode = currentNode.getNextSibling();

            if (previousNode != null && nextNode != null) {
                boolean currentNodeMatches = currentNode.getNodeName().equals(ELEM_BR);
                boolean previousNodeMatches = previousNode.getNodeType() == Node.TEXT_NODE
                        && previousNode.getTextContent().matches(regex);
                boolean nextNodeMatches = nextNode.getNodeType() == Node.TEXT_NODE
                        && nextNode.getTextContent().matches(regex);

                assertFalse(Type.ERROR, "rpd3s13.lists",
                        previousNodeMatches && currentNodeMatches && nextNodeMatches);
            }

            previousNode = currentNode;
        }
    }
}

From source file:ro.agrade.jira.qanda.dao.GenericDelegatorLoader.java

/**
 * Add the associations "entity name"-"group name" from the xml file
 * represented by the ResourceHandler rh to the group cache from the model
 * reader modelGroupR. The code is a part from getGroupCache() method from
 * ModelGroupReader class./*  ww  w  .j a v  a2s  .c o m*/
 * 
 * @param modelGroupReader The model group reader.
 * @param resourceHandler The resource handler for entity groups associations.
 * @throws OfbizDataException if an error occurs when adding groups to
 * group cache
 */
private void addGroupsToGroupCache(ModelGroupReader modelGroupReader, ResourceHandler resourceHandler)
        throws OfbizDataException {
    if (modelGroupReader == null || resourceHandler == null) {
        LOG.warn(String.format("Null timereport group reader or resource "
                + "handler in addGroupsToGroupCache() method." + " Model reader: %s resource handler: %s",
                modelGroupReader, resourceHandler));
        return;
    }
    try {
        Map<?, ?> groupCache = modelGroupReader.getGroupCache();
        Document document;

        synchronized (ModelGroupReader.class) {

            try {
                document = resourceHandler.getDocument();
            } catch (GenericConfigException e) {
                String msg = "Error loading entity group timereport";
                LOG.error(msg, e);
                throw new OfbizDataException(msg, e);
            }
            if (document == null) {
                String msg = String.format("Could not get document for %s", resourceHandler);
                LOG.error(msg);
                throw new OfbizDataException(msg);
            }

            Element docElement = document.getDocumentElement();

            if (docElement == null) {
                String msg = "NULL doc element.";
                LOG.error(msg);
                throw new OfbizDataException(msg);
            }
            docElement.normalize();
            Node curChild = docElement.getFirstChild();

            if (curChild != null) {
                do {
                    if (curChild.getNodeType() == Node.ELEMENT_NODE
                            && "entity-group".equals(curChild.getNodeName())) {
                        Element curEntity = (Element) curChild;
                        String entityName = UtilXml.checkEmpty(curEntity.getAttribute("entity"));
                        String groupName = UtilXml.checkEmpty(curEntity.getAttribute("group"));

                        if (groupName == null || entityName == null) {
                            continue;
                        }
                        safelyMapAdd(groupCache, entityName, groupName);
                    }
                } while ((curChild = curChild.getNextSibling()) != null);
            } else {
                LOG.warn("[addGroupsToGroupCache()] No child nodes found.");
            }
        }
    } catch (Exception ex) {
        String msg = String.format("Got exception when adding groups " + "from resource handler: %s",
                resourceHandler);
        LOG.error(msg, ex);
        throw new OfbizDataException(msg, ex);
    }
}

From source file:ro.agrade.jira.qanda.dao.GenericDelegatorLoader.java

/**
 * Add the model entities from the xml file represented by the
 * ResourceHandler rhEntity to the entity cache from the model reader
 * modelR. The code is(with little changes) a part from getEntityCache()
 * method in ModelReader class./*from   w ww .jav a  2  s  . c o  m*/
 * 
 * @param modelReader The model reader.
 * @param resourceHandler The resource handler.
 * @param loaderEnt The loader name for the xml for entities.
 * @param locationEnt The location for the xml file for entities.
 * @throws OfbizDataException if an error occurs when adding entities to
 * entity cache
 */
private void addEntitiesToEntityCache(ModelReader modelReader, ResourceHandler resourceHandler,
        String loaderEnt, String locationEnt) throws OfbizDataException {
    if (modelReader == null || resourceHandler == null) {
        LOG.warn(
                String.format("Null reader or resource handler" + " in addEntitiesToEntityCache() method. Model"
                        + " reader: %s Resource handler: %s", modelReader, resourceHandler));
        return;
    }
    try {
        Document document;
        Map<String, ModelEntity> entityCache = modelReader.getEntityCache();
        List<ModelViewEntity> tempViewEntityList = new LinkedList<ModelViewEntity>();
        Hashtable<String, String> docElementValues = new Hashtable<String, String>();

        synchronized (ModelReader.class) {
            try {
                document = resourceHandler.getDocument();
            } catch (GenericConfigException e) {
                String msg = "Error getting document from resource handler";
                LOG.error(msg);
                throw new GenericEntityConfException(msg, e);
            }
            if (document == null) {
                String msg = String.format("Could not get document for %s", resourceHandler);
                LOG.error(msg);
                throw new OfbizDataException(msg);
            }

            Element docElement = document.getDocumentElement();

            if (docElement == null) {
                String msg = "NULL doc element.";
                LOG.error(msg);
                throw new OfbizDataException(msg);
            }
            docElement.normalize();
            Node curChild = docElement.getFirstChild();

            int i = 0;

            if (curChild != null) {
                do {
                    boolean isEntity = "entity".equals(curChild.getNodeName());
                    boolean isViewEntity = "view-entity".equals(curChild.getNodeName());

                    if ((isEntity || isViewEntity) && curChild.getNodeType() == Node.ELEMENT_NODE) {
                        i++;
                        Element curEntity = (Element) curChild;
                        String entityName = UtilXml.checkEmpty(curEntity.getAttribute("entity-name"));

                        // check to see if entity with same name has already
                        // been read
                        if (entityCache.containsKey(entityName)) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug(String.format("Entity %s is defined more than once, most "
                                        + "recent will overwrite previous definition", entityName));
                            }
                        }

                        // add entity to entityResourceHandlerMap map
                        modelReader.addEntityToResourceHandler(entityName, loaderEnt, locationEnt);

                        ModelEntity entity;

                        if (isEntity) {
                            entity = createModelEntity(modelReader, curEntity, docElement, null,
                                    docElementValues);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug(String.format("[Entity]: # %d: %s", i, entityName));
                            }
                        } else {
                            entity = createModelViewEntity(modelReader, curEntity, docElement, null,
                                    docElementValues);
                            // put the view entity in a list to get ready
                            // for the second pass to populate fields...
                            tempViewEntityList.add((ModelViewEntity) entity);
                            if (LOG.isDebugEnabled()) {
                                String msg = String.format("[ViewEntity]: # %d: %s", i, entityName);
                                LOG.debug(msg);
                            }
                        }

                        if (entity != null) {
                            safelyMapAdd(entityCache, entityName, entity);
                        } else {
                            LOG.warn(String.format("Could not create entity " + "for entityName: %s",
                                    entityName));
                        }
                    }
                } while ((curChild = curChild.getNextSibling()) != null);
            } else {
                LOG.warn("No child nodes found.");
            }

            modelReader.rebuildResourceHandlerEntities();

            // do a pass on all of the view entities now that all of the
            // entities have loaded and populate the fields
            for (ModelViewEntity me : tempViewEntityList) {
                me.populateFields(entityCache);
            }
            LOG.debug("FINISHED LOADING ENTITIES.");
        }
    } catch (Exception ex) {
        String msg = String.format("Got exception when adding entities " + "from resource handler: %s",
                resourceHandler);
        LOG.error(msg, ex);
        throw new OfbizDataException(msg, ex);
    }
}