Example usage for org.w3c.dom Node COMMENT_NODE

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

Introduction

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

Prototype

short COMMENT_NODE

To view the source code for org.w3c.dom Node COMMENT_NODE.

Click Source Link

Document

The node is a Comment.

Usage

From source file:org.erdc.cobie.shared.spreadsheetml.transformation.cobietab.COBieSpreadSheet.java

License:asdf

public static void nodeToStream(Node node, PrintWriter out) {
    String workSheetName = "";
    boolean canonical = false;
    // is there anything to do?
    if (node == null) {
        return;/* www .  ja  v  a 2  s.  c om*/
    }

    int type = node.getNodeType();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        if (!canonical) {
            out.println("<?xml version=\"1.0\"?>");
        }
        // print(((Document)node).getDocumentElement());

        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            nodeToStream(children.item(iChild), out);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            if (((node.getNodeName().equalsIgnoreCase("Worksheet")
                    || node.getNodeName().equalsIgnoreCase("ss:Worksheet"))
                    && attr.getName().equalsIgnoreCase("Name")) || attr.getName().equalsIgnoreCase("ss:Name")) {
                workSheetName = normalize(attr.getNodeValue());
            }
            out.print(' ');
            out.print(attr.getNodeName());
            out.print("=\"");
            out.print(normalize(attr.getNodeValue()));
            out.print('"');
        }
        out.print('>');
        out.flush();
        NodeList children = node.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                nodeToStream(children.item(i), out);
            }
        }
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    nodeToStream(children.item(i), out);
                }
            }
        } else {
            out.print('&');
            out.print(node.getNodeName());
            out.print(';');
        }
        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        if (canonical) {
            out.print(normalize(node.getNodeValue()));
        } else {
            out.print("<![CDATA[");
            out.print(node.getNodeValue());
            out.print("]]>");
        }
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String data = node.getNodeValue();
        if ((data != null) && (data.length() > 0)) {
            out.print(' ');
            out.print(data);
        }
        out.print("?>");
        break;
    }

    // print comment
    case Node.COMMENT_NODE: {
        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");
        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if ((node.getNodeName().equalsIgnoreCase("Worksheet")
                || node.getNodeName().equalsIgnoreCase("ss:Worksheet")) && (workSheetName.length() > 0)) {
            out.print(printCOBieSheetDataValidation(workSheetName));
        }
        out.print("</");
        out.print(node.getNodeName());
        out.print('>');
    }

    out.flush();

}

From source file:org.exist.dom.ElementImpl.java

private Node appendChild(Txn transaction, NodeId newNodeId, NodeImplRef last, NodePath lastPath, Node child,
        StreamListener listener) throws DOMException {
    if (last == null || last.getNode() == null)
    //TODO : same test as above ? -pb
    {//w  w w.j a v a 2  s .com
        throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "invalid node");
    }
    final DocumentImpl owner = (DocumentImpl) getOwnerDocument();
    DBBroker broker = null;
    try {
        broker = ownerDocument.getBrokerPool().get(null);
        switch (child.getNodeType()) {
        case Node.DOCUMENT_FRAGMENT_NODE:
            appendChildren(transaction, newNodeId, null, last, lastPath, child.getChildNodes(), listener);
            return null; // TODO: implement document fragments so
        //we can return all newly appended children
        case Node.ELEMENT_NODE:
            // create new element
            final ElementImpl elem = new ElementImpl(
                    new QName(child.getLocalName() == null ? child.getNodeName() : child.getLocalName(),
                            child.getNamespaceURI(), child.getPrefix()),
                    broker.getBrokerPool().getSymbols());
            elem.setNodeId(newNodeId);
            elem.setOwnerDocument(owner);
            final NodeListImpl ch = new NodeListImpl();
            final NamedNodeMap attribs = child.getAttributes();
            int numActualAttribs = 0;
            for (int i = 0; i < attribs.getLength(); i++) {
                final Attr attr = (Attr) attribs.item(i);
                if (!attr.getNodeName().startsWith("xmlns")) {
                    ch.add(attr);
                    numActualAttribs++;
                } else {
                    final String xmlnsDecl = attr.getNodeName();
                    final String prefix = xmlnsDecl.length() == 5 ? "" : xmlnsDecl.substring(6);
                    elem.addNamespaceMapping(prefix, attr.getNodeValue());
                }
            }
            final NodeList cl = child.getChildNodes();
            for (int i = 0; i < cl.getLength(); i++) {
                final Node n = cl.item(i);
                if (n.getNodeType() != Node.ATTRIBUTE_NODE) {
                    ch.add(n);
                }
            }
            elem.setChildCount(ch.getLength());
            if (numActualAttribs != (short) numActualAttribs) {
                throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "Too many attributes");
            }
            elem.setAttributes((short) numActualAttribs);
            lastPath.addComponent(elem.getQName());
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), elem);
            broker.indexNode(transaction, elem, lastPath);
            broker.getIndexController().indexNode(transaction, elem, lastPath, listener);
            elem.setChildCount(0);
            last.setNode(elem);
            //process child nodes
            elem.appendChildren(transaction, newNodeId.newChild(), null, last, lastPath, ch, listener);
            broker.endElement(elem, lastPath, null);
            broker.getIndexController().endElement(transaction, elem, lastPath, listener);
            lastPath.removeLastComponent();
            return elem;
        case Node.TEXT_NODE:
            final TextImpl text = new TextImpl(newNodeId, ((Text) child).getData());
            text.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), text);
            broker.indexNode(transaction, text, lastPath);
            broker.getIndexController().indexNode(transaction, text, lastPath, listener);
            last.setNode(text);
            return text;
        case Node.CDATA_SECTION_NODE:
            final CDATASectionImpl cdata = new CDATASectionImpl(newNodeId, ((CDATASection) child).getData());
            cdata.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), cdata);
            broker.indexNode(transaction, cdata, lastPath);
            last.setNode(cdata);
            return cdata;
        case Node.ATTRIBUTE_NODE:
            final Attr attr = (Attr) child;
            final String ns = attr.getNamespaceURI();
            final String prefix = (Namespaces.XML_NS.equals(ns) ? "xml" : attr.getPrefix());
            String name = attr.getLocalName();
            if (name == null) {
                name = attr.getName();
            }
            final QName attrName = new QName(name, ns, prefix);
            final AttrImpl attrib = new AttrImpl(attrName, attr.getValue(),
                    broker.getBrokerPool().getSymbols());
            attrib.setNodeId(newNodeId);
            attrib.setOwnerDocument(owner);
            if (ns != null && attrName.compareTo(Namespaces.XML_ID_QNAME) == Constants.EQUAL) {
                // an xml:id attribute. Normalize the attribute and set its type to ID
                attrib.setValue(StringValue.trimWhitespace(StringValue.collapseWhitespace(attrib.getValue())));
                attrib.setType(AttrImpl.ID);
            } else {
                attrName.setNameType(ElementValue.ATTRIBUTE);
            }
            broker.insertNodeAfter(transaction, last.getNode(), attrib);
            broker.indexNode(transaction, attrib, lastPath);
            broker.getIndexController().indexNode(transaction, attrib, lastPath, listener);
            last.setNode(attrib);
            return attrib;
        case Node.COMMENT_NODE:
            final CommentImpl comment = new CommentImpl(((Comment) child).getData());
            comment.setNodeId(newNodeId);
            comment.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), comment);
            broker.indexNode(transaction, comment, lastPath);
            last.setNode(comment);
            return comment;
        case Node.PROCESSING_INSTRUCTION_NODE:
            final ProcessingInstructionImpl pi = new ProcessingInstructionImpl(newNodeId,
                    ((ProcessingInstruction) child).getTarget(), ((ProcessingInstruction) child).getData());
            pi.setOwnerDocument(owner);
            //insert the node
            broker.insertNodeAfter(transaction, last.getNode(), pi);
            broker.indexNode(transaction, pi, lastPath);
            last.setNode(pi);
            return pi;
        default:
            throw new DOMException(DOMException.INVALID_MODIFICATION_ERR,
                    "Unknown node type: " + child.getNodeType() + " " + child.getNodeName());
        }
    } catch (final EXistException e) {
        LOG.warn("Exception while appending node: " + e.getMessage(), e);
    } finally {
        if (broker != null)
            broker.release();
    }
    return null;
}

From source file:org.exist.storage.dom.DOMFile.java

/**
 * Recursive method to retrieve the string values of the root node
 * and all its descendants./*from   w  ww.  ja  v  a 2s.  com*/
 */
private void getNodeValue(BrokerPool pool, DocumentImpl doc, ByteArrayOutputStream os, RecordPos rec,
        boolean isTopNode, boolean addWhitespace) {
    if (!lock.hasLock()) {
        LOG.warn("The file doesn't own a lock");
    }
    //Locate the next real node, skipping relocated nodes
    boolean foundNext = false;
    do {
        final DOMFilePageHeader pageHeader = rec.getPage().getPageHeader();
        if (rec.offset > pageHeader.getDataLength()) {
            // end of page reached, proceed to the next page
            final long nextPage = pageHeader.getNextDataPage();
            if (nextPage == Page.NO_PAGE) {
                SanityCheck.TRACE("Bad link to next page! " + "Offset: " + rec.offset + ", Len: "
                        + pageHeader.getDataLength() + ", Page info : " + rec.getPage().page.getPageInfo());
                //TODO : throw exception ? -pb
                return;
            }
            rec.setPage(getDOMPage(nextPage));
            dataCache.add(rec.getPage());
            rec.offset = LENGTH_TID;
        }
        //Position the stream at the very beginning of the record
        final short tupleID = ByteConversion.byteToShort(rec.getPage().data, rec.offset - LENGTH_TID);
        rec.setTupleID(tupleID);
        if (ItemId.isLink(rec.getTupleID())) {
            //This is a link: skip it
            //We position the offset *after* the next TupleID
            rec.offset += (LENGTH_FORWARD_LOCATION + LENGTH_TID);
        } else {
            //OK: node found
            foundNext = true;
        }
    } while (!foundNext);
    final short valueLength = ByteConversion.byteToShort(rec.getPage().data, rec.offset);
    int realLen = valueLength;
    rec.offset += LENGTH_DATA_LENGTH;
    //Check if the node was relocated
    if (ItemId.isRelocated(rec.getTupleID())) {
        rec.offset += LENGTH_ORIGINAL_LOCATION;
    }
    byte[] data = rec.getPage().data;
    int readOffset = rec.offset;
    boolean inOverflow = false;
    if (valueLength == OVERFLOW) {
        //If we have an overflow value, load it from the overflow page
        final long p = ByteConversion.byteToLong(data, rec.offset);
        data = getOverflowValue(p);
        //We position the offset *after* the next TID
        rec.offset += LENGTH_OVERFLOW_LOCATION + LENGTH_TID;
        realLen = data.length;
        readOffset = 0;
        inOverflow = true;
    }
    // check the type of the node
    final short type = Signatures.getType(data[readOffset]);
    readOffset += StoredNode.LENGTH_SIGNATURE_LENGTH;
    //Switch on the node type
    switch (type) {
    case Node.ELEMENT_NODE: {
        final int children = ByteConversion.byteToInt(data, readOffset);
        readOffset += ElementImpl.LENGTH_ELEMENT_CHILD_COUNT;
        final int dlnLen = ByteConversion.byteToShort(data, readOffset);
        readOffset += NodeId.LENGTH_NODE_ID_UNITS;
        final int nodeIdLen = pool.getNodeFactory().lengthInBytes(dlnLen, data, readOffset);
        readOffset += nodeIdLen;
        final short attributes = ByteConversion.byteToShort(data, readOffset);
        //Ignore the following NS data which are of no use
        //We position the offset *after* the next TID
        rec.offset += realLen + LENGTH_TID;
        final boolean extraWhitespace = addWhitespace && (children - attributes) > 1;
        for (int i = 0; i < children; i++) {
            //recursive call : we ignore attributes children
            getNodeValue(pool, doc, os, rec, false, addWhitespace);
            if (extraWhitespace) {
                os.write((byte) ' ');
            }
        }
        return;
    }
    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE: {
        final int dlnLen = ByteConversion.byteToShort(data, readOffset);
        readOffset += NodeId.LENGTH_NODE_ID_UNITS;
        final int nodeIdLen = pool.getNodeFactory().lengthInBytes(dlnLen, data, readOffset);
        readOffset += nodeIdLen;
        os.write(data, readOffset,
                realLen - (StoredNode.LENGTH_SIGNATURE_LENGTH + NodeId.LENGTH_NODE_ID_UNITS + nodeIdLen));
        break;
    }
    case Node.PROCESSING_INSTRUCTION_NODE: {
        final int dlnLen = ByteConversion.byteToShort(data, readOffset);
        readOffset += NodeId.LENGTH_NODE_ID_UNITS;
        final int nodeIdLen = pool.getNodeFactory().lengthInBytes(dlnLen, data, readOffset);
        readOffset += nodeIdLen;
        final int targetLen = ByteConversion.byteToInt(data, readOffset);
        readOffset += 4 + targetLen;
        os.write(data, readOffset, realLen - (StoredNode.LENGTH_SIGNATURE_LENGTH + NodeId.LENGTH_NODE_ID_UNITS
                + nodeIdLen + targetLen + 4));
        break;
    }
    case Node.ATTRIBUTE_NODE: {
        if (isTopNode) {
            final int start = readOffset - StoredNode.LENGTH_SIGNATURE_LENGTH;
            final byte idSizeType = (byte) (data[start] & 0x3);
            final boolean hasNamespace = (data[start] & 0x10) == 0x10;
            final int dlnLen = ByteConversion.byteToShort(data, readOffset);
            readOffset += NodeId.LENGTH_NODE_ID_UNITS;
            final int nodeIdLen = pool.getNodeFactory().lengthInBytes(dlnLen, data, readOffset);
            readOffset += nodeIdLen;
            readOffset += Signatures.getLength(idSizeType);
            if (hasNamespace) {
                readOffset += AttrImpl.LENGTH_NS_ID; // skip namespace id
                final short prefixLen = ByteConversion.byteToShort(data, readOffset);
                readOffset += AttrImpl.LENGTH_PREFIX_LENGTH;
                readOffset += prefixLen; // skip prefix
            }
            os.write(data, readOffset, realLen - (readOffset - start));
        }
        break;
    }
    case Node.COMMENT_NODE: {
        if (isTopNode) {
            final int dlnLen = ByteConversion.byteToShort(data, readOffset);
            readOffset += NodeId.LENGTH_NODE_ID_UNITS;
            final int nodeIdLen = pool.getNodeFactory().lengthInBytes(dlnLen, data, readOffset);
            readOffset += nodeIdLen;
            os.write(data, readOffset,
                    realLen - (StoredNode.LENGTH_SIGNATURE_LENGTH + NodeId.LENGTH_NODE_ID_UNITS + nodeIdLen));
        }
        break;
    }
    }
    if (!inOverflow) {
        //If it isn't an overflow value, add the value length to the current offset
        //We position the offset *after* the next TID
        rec.offset += realLen + LENGTH_TID;
    }
}

From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java

private boolean isTextOrComment(Node node) {
    return node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.COMMENT_NODE;
}

From source file:org.getobjects.appserver.templates.WOxElemBuilder.java

public WOElement buildNode(Node _node, WOxElemBuilder _builder) {
    if (_node == null)
        return null;

    switch (_node.getNodeType()) {
    case Node.ELEMENT_NODE:
        return this.buildElement((Element) _node, _builder);
    case Node.TEXT_NODE:
        return this.buildText((Text) _node, _builder);
    case Node.CDATA_SECTION_NODE:
        return this.buildCDATASection((CDATASection) _node, _builder);
    case Node.COMMENT_NODE:
        return this.buildComment((Comment) _node, _builder);
    case Node.DOCUMENT_NODE:
        return this.buildDocument((Document) _node, _builder);

    default: {/*  w  ww .j a v  a 2  s .  c  o  m*/
        if (this.nextBuilder != null)
            return this.nextBuilder.buildNode(_node, _builder);

        this.log.error("unsupported node type: " + _node);
    }
    }
    return null;
}

From source file:org.jahia.utils.PomUtils.java

/**
 * Serializes Maven project model into a specified file.
 * /*from  w  ww.  j  a v  a 2s.c  o m*/
 * @param model
 *            the Maven project model to serialize
 * @param targetPomXmlFile
 *            the target file to write the provided model into
 * @throws IOException
 *             in case of a serialization error
 */
public static void write(Model model, File targetPomXmlFile) throws IOException {
    String copyright = null;
    try {
        DocumentBuilder docBuilder = JahiaDocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.parse(targetPomXmlFile);
        Node firstChild = doc.getFirstChild();
        if (firstChild.getNodeType() == Node.COMMENT_NODE) {
            copyright = firstChild.getTextContent();
        }
    } catch (Exception e) {
        logger.warn("Failed to read pom.xml copyright", e);
    }

    MavenXpp3Writer xpp3Writer = new MavenXpp3Writer();
    OutputStream os = null;
    String pomContent;
    try {
        os = new ByteArrayOutputStream();
        xpp3Writer.write(os, model);
        pomContent = os.toString();
    } finally {
        IOUtils.closeQuietly(os);
    }

    if (copyright != null) {
        int i = pomContent.indexOf("<project");
        pomContent = pomContent.substring(0, i) + "<!--" + copyright + "-->\n" + pomContent.substring(i);
    }

    org.apache.commons.io.FileUtils.write(targetPomXmlFile, pomContent);
}

From source file:org.nuxeo.theme.themes.ThemeParser.java

private static String getCommentAssociatedTo(Node node) {
    Node n = node;/*from w  w  w .j a va  2  s.  co  m*/
    while (true) {
        n = n.getPreviousSibling();
        if (n == null) {
            break;
        }
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            break;
        }
        if (n.getNodeType() == Node.COMMENT_NODE) {
            return n.getNodeValue().trim();
        }
    }
    return null;
}

From source file:org.openengsb.openengsbplugin.base.ConfiguredMojo.java

protected void tryExtractLicenseHeader(Document doc) {
    Node firstNode = doc.getChildNodes().item(0);
    if (firstNode.getNodeType() == Node.COMMENT_NODE) {
        LOG.trace(String.format("found license header with content:\n%s", firstNode.getNodeValue()));
        licenseHeaderComment = doc.removeChild(firstNode);
    }/*  ww  w  .  j  a  v  a  2 s  . c  om*/
}

From source file:org.openestate.io.core.XmlUtils.java

/**
 * Recursively remove any comments and unnecessary white spaces from a
 * {@link Node} and its children./*ww  w .j  a v  a 2  s  .co  m*/
 *
 * @param node
 * the node to clean
 */
public static void clean(Node node) {
    NodeList childNodes = node.getChildNodes();
    for (int n = childNodes.getLength() - 1; n >= 0; n--) {
        Node child = childNodes.item(n);
        short nodeType = child.getNodeType();
        if (nodeType == Node.ELEMENT_NODE) {
            XmlUtils.clean(child);
        } else if (nodeType == Node.COMMENT_NODE) {
            node.removeChild(child);
        } else if (nodeType == Node.TEXT_NODE) {
            String value = StringUtils.trimToNull(child.getNodeValue());
            if (value == null)
                node.removeChild(child);
            else
                child.setNodeValue(value);
        }
    }
}

From source file:org.owasp.webscarab.plugin.saml.SamlModel.java

private boolean isDigested(NodeList nodes, VerifyReference[] references) {
    for (int idx = 0; idx < nodes.getLength(); idx++) {
        Node node = nodes.item(idx);
        //this._logger.log(Level.FINE, "node name: {0}", node.getLocalName());
        boolean changed = false;
        if (node.getNodeType() == Node.TEXT_NODE) {
            String originalTextValue = node.getNodeValue();
            String changedTextValue = originalTextValue + "foobar";
            node.setNodeValue(changedTextValue);
            changed = false; // need to have impact anyway
            for (int referenceIdx = 0; referenceIdx < references.length; referenceIdx++) {
                VerifyReference reference = references[referenceIdx];
                changed |= reference.hasChanged();
            }//w  w w. j  a  v a  2  s  .com
            if (false == changed) {
                return false;
            }
            node.setNodeValue(originalTextValue);
        } else if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;

            NamedNodeMap attributes = element.getAttributes();
            for (int attributeIdx = 0; attributeIdx < attributes.getLength(); attributeIdx++) {
                Node attributeNode = attributes.item(attributeIdx);
                String originalAttributeValue = attributeNode.getNodeValue();
                String changedAttributeValue = originalAttributeValue + "foobar";
                attributeNode.setNodeValue(changedAttributeValue);
                for (int referenceIdx = 0; referenceIdx < references.length; referenceIdx++) {
                    VerifyReference reference = references[referenceIdx];
                    changed |= reference.hasChanged();
                }

                attributeNode.setNodeValue(originalAttributeValue);
            }
            changed |= isDigested(element.getChildNodes(), references);
        } else if (node.getNodeType() == Node.COMMENT_NODE) {
            // not always digested by the ds:References
        } else {
            throw new RuntimeException("unsupported node type: " + node.getNodeType());
        }
        if (false == changed) {
            return false;
        }
    }
    return true;
}