Search in sources :

Example 46 with NamedNodeMap

use of org.w3c.dom.NamedNodeMap in project sling by apache.

the class MyErrorHandler method convert.

// ------------------------------------------------------ Protected Methods
/**
     * Create and return a TreeNode that corresponds to the specified Node,
     * including processing all of the attributes and children nodes.
     *
     * @param parent The parent TreeNode (if any) for the new TreeNode
     * @param node The XML document Node to be converted
     */
protected TreeNode convert(TreeNode parent, Node node) {
    // Construct a new TreeNode for this node
    TreeNode treeNode = new TreeNode(node.getNodeName(), parent);
    // Convert all attributes of this node
    NamedNodeMap attributes = node.getAttributes();
    if (attributes != null) {
        int n = attributes.getLength();
        for (int i = 0; i < n; i++) {
            Node attribute = attributes.item(i);
            treeNode.addAttribute(attribute.getNodeName(), attribute.getNodeValue());
        }
    }
    // Create and attach all children of this node
    NodeList children = node.getChildNodes();
    if (children != null) {
        int n = children.getLength();
        for (int i = 0; i < n; i++) {
            Node child = children.item(i);
            if (child instanceof Comment)
                continue;
            if (child instanceof Text) {
                String body = ((Text) child).getData();
                if (body != null) {
                    body = body.trim();
                    if (body.length() > 0)
                        treeNode.setBody(body);
                }
            } else {
                TreeNode treeChild = convert(treeNode, child);
            }
        }
    }
    // Return the completed TreeNode graph
    return (treeNode);
}
Also used : Comment(org.w3c.dom.Comment) NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Text(org.w3c.dom.Text)

Example 47 with NamedNodeMap

use of org.w3c.dom.NamedNodeMap in project intellij-community by JetBrains.

the class FindJarFix method findJarsForFqn.

private void findJarsForFqn(final String fqn, final Editor editor) {
    final Map<String, String> libs = new HashMap<>();
    final Runnable runnable = () -> {
        try {
            final DOMParser parser = new DOMParser();
            parser.parse(CLASS_ROOT_URL + fqn.replace('.', '/') + CLASS_PAGE_EXT);
            final Document doc = parser.getDocument();
            if (doc != null) {
                final NodeList links = doc.getElementsByTagName(LINK_TAG_NAME);
                for (int i = 0; i < links.getLength(); i++) {
                    final Node link = links.item(i);
                    final String libName = link.getTextContent();
                    final NamedNodeMap attributes = link.getAttributes();
                    if (attributes != null) {
                        final Node href = attributes.getNamedItem(LINK_ATTR_NAME);
                        if (href != null) {
                            final String pathToJar = href.getTextContent();
                            if (pathToJar != null && (pathToJar.startsWith("/jar/") || pathToJar.startsWith("/class/../"))) {
                                libs.put(libName, SERVICE_URL + pathToJar);
                            }
                        }
                    }
                }
            }
        } catch (IOException ignore) {
        //
        } catch (Exception e) {
            //
            LOG.warn(e);
        }
    };
    final Task.Modal task = new Task.Modal(editor.getProject(), "Looking for libraries", true) {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            runUncanceledRunnableWithProgress(runnable, indicator);
        }

        @Override
        public void onSuccess() {
            super.onSuccess();
            if (libs.isEmpty()) {
                HintManager.getInstance().showInformationHint(editor, "No libraries found for '" + fqn + "'");
            } else {
                final ArrayList<String> variants = new ArrayList<>(libs.keySet());
                Collections.sort(variants, (o1, o2) -> o1.compareTo(o2));
                final JBList libNames = new JBList(variants);
                libNames.installCellRenderer(o -> new JLabel(o.toString(), PlatformIcons.JAR_ICON, SwingConstants.LEFT));
                if (libs.size() == 1) {
                    final String jarName = libs.keySet().iterator().next();
                    final String url = libs.get(jarName);
                    initiateDownload(url, jarName);
                } else {
                    JBPopupFactory.getInstance().createListPopupBuilder(libNames).setTitle("Select a JAR file").setItemChoosenCallback(() -> {
                        final Object value = libNames.getSelectedValue();
                        if (value instanceof String) {
                            final String jarName = (String) value;
                            final String url = libs.get(jarName);
                            if (url != null) {
                                initiateDownload(url, jarName);
                            }
                        }
                    }).createPopup().showInBestPositionFor(editor);
                }
            }
        }
    };
    ProgressManager.getInstance().run(task);
}
Also used : Task(com.intellij.openapi.progress.Task) NamedNodeMap(org.w3c.dom.NamedNodeMap) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) NotNull(org.jetbrains.annotations.NotNull) IncorrectOperationException(com.intellij.util.IncorrectOperationException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) JBList(com.intellij.ui.components.JBList) DOMParser(org.cyberneko.html.parsers.DOMParser)

Example 48 with NamedNodeMap

use of org.w3c.dom.NamedNodeMap in project poi by apache.

the class AbstractWordUtils method canBeMerged.

static boolean canBeMerged(Node node1, Node node2, String requiredTagName) {
    if (node1.getNodeType() != Node.ELEMENT_NODE || node2.getNodeType() != Node.ELEMENT_NODE)
        return false;
    Element element1 = (Element) node1;
    Element element2 = (Element) node2;
    if (!equals(requiredTagName, element1.getTagName()) || !equals(requiredTagName, element2.getTagName()))
        return false;
    NamedNodeMap attributes1 = element1.getAttributes();
    NamedNodeMap attributes2 = element2.getAttributes();
    if (attributes1.getLength() != attributes2.getLength())
        return false;
    for (int i = 0; i < attributes1.getLength(); i++) {
        final Attr attr1 = (Attr) attributes1.item(i);
        final Attr attr2;
        if (isNotEmpty(attr1.getNamespaceURI()))
            attr2 = (Attr) attributes2.getNamedItemNS(attr1.getNamespaceURI(), attr1.getLocalName());
        else
            attr2 = (Attr) attributes2.getNamedItem(attr1.getName());
        if (attr2 == null || !equals(attr1.getTextContent(), attr2.getTextContent()))
            return false;
    }
    return true;
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) Element(org.w3c.dom.Element) Attr(org.w3c.dom.Attr)

Example 49 with NamedNodeMap

use of org.w3c.dom.NamedNodeMap in project nokogiri by sparklemotion.

the class DOM2DTMExt method nextNode.

/**
     * This method iterates to the next node that will be added to the table.
     * Each call to this method adds a new node to the table, unless the end
     * is reached, in which case it returns null.
     *
     * @return The true if a next node is found or false if
     *         there are no more nodes.
     */
protected boolean nextNode() {
    // we've avoided most of the special cases.
    if (m_nodesAreProcessed)
        return false;
    // %REVIEW% Is this local copy Really Useful from a performance
    // point of view?  Or is this a false microoptimization?
    Node pos = m_pos;
    Node next = null;
    int nexttype = NULL;
    // Navigate DOM tree
    do {
        // Look down to first child.
        if (pos.hasChildNodes()) {
            next = pos.getFirstChild();
            // the doctype. (Just let it go and Suppress it?
            if (next != null && DOCUMENT_TYPE_NODE == next.getNodeType())
                next = next.getNextSibling();
            // which have no DTM equivalent and cause no DTM navigation.
            if (ENTITY_REFERENCE_NODE != pos.getNodeType()) {
                m_last_parent = m_last_kid;
                m_last_kid = NULL;
                // Whitespace-handler context stacking
                if (null != m_wsfilter) {
                    short wsv = m_wsfilter.getShouldStripSpace(makeNodeHandle(m_last_parent), this);
                    boolean shouldStrip = (DTMWSFilter.INHERIT == wsv) ? getShouldStripWhitespace() : (DTMWSFilter.STRIP == wsv);
                    pushShouldStripWhitespace(shouldStrip);
                }
            // if(m_wsfilter)
            }
        } else // If that fails, look up and right (but not past root!)
        {
            if (m_last_kid != NULL) {
                // If it has _no_ children, we need to record that.
                if (m_firstch.elementAt(m_last_kid) == NOTPROCESSED)
                    m_firstch.setElementAt(NULL, m_last_kid);
            }
            while (m_last_parent != NULL) {
                // %REVIEW% There's probably a more elegant way to
                // skip the doctype. (Just let it go and Suppress it?
                next = pos.getNextSibling();
                if (next != null && DOCUMENT_TYPE_NODE == next.getNodeType())
                    next = next.getNextSibling();
                if (next != null)
                    // Found it!
                    break;
                // No next-sibling found. Pop the DOM.
                pos = pos.getParentNode();
                // encounter one, pop it _without_ popping DTM.
                if (pos != null && ENTITY_REFERENCE_NODE == pos.getNodeType()) {
                //                        // Nothing needs doing
                //                        if(JJK_DEBUG) System.out.println("***** DOM2DTM popping EntRef");
                } else {
                    popShouldStripWhitespace();
                    // Fix and pop DTM
                    if (m_last_kid == NULL)
                        // Popping from an element
                        m_firstch.setElementAt(NULL, m_last_parent);
                    else
                        // Popping from anything else
                        m_nextsib.setElementAt(NULL, m_last_kid);
                    m_last_parent = m_parent.elementAt(m_last_kid = m_last_parent);
                }
            }
            if (m_last_parent == NULL)
                next = null;
        }
        if (next != null)
            nexttype = next.getNodeType();
        // it doesn't happen very often. We'd get rid of the loop too.
        if (ENTITY_REFERENCE_NODE == nexttype)
            pos = next;
    } while (ENTITY_REFERENCE_NODE == nexttype);
    // Did we run out of the tree?
    if (next == null) {
        m_nextsib.setElementAt(NULL, 0);
        m_nodesAreProcessed = true;
        m_pos = null;
        return false;
    }
    // Text needs some special handling:
    //
    // DTM may skip whitespace. This is handled by the suppressNode flag, which
    // when true will keep the DTM node from being created.
    //
    // DTM only directly records the first DOM node of any logically-contiguous
    // sequence. The lastTextNode value will be set to the last node in the
    // contiguous sequence, and -- AFTER the DTM addNode -- can be used to
    // advance next over this whole block. Should be simpler than special-casing
    // the above loop for "Was the logically-preceeding sibling a text node".
    //
    // Finally, a DTM node should be considered a CDATASection only if all the
    // contiguous text it covers is CDATASections. The first Text should
    // force DTM to Text.
    boolean suppressNode = false;
    Node lastTextNode = null;
    nexttype = next.getNodeType();
    // nexttype=pos.getNodeType();
    if (TEXT_NODE == nexttype || CDATA_SECTION_NODE == nexttype) {
        // If filtering, initially assume we're going to suppress the node
        suppressNode = ((null != m_wsfilter) && getShouldStripWhitespace());
        // of entity reference boundaries).
        if (suppressNode) {
            Node n = next;
            while (n != null) {
                lastTextNode = n;
                // Any Text node means DTM considers it all Text
                if (TEXT_NODE == n.getNodeType())
                    nexttype = TEXT_NODE;
                // Any non-whitespace in this sequence blocks whitespace
                // suppression
                suppressNode &= XMLCharacterRecognizer.isWhiteSpace(n.getNodeValue());
                n = logicalNextDOMTextNode(n);
            }
        }
    } else // 3. We want to recognize and reject that case.
    if (PROCESSING_INSTRUCTION_NODE == nexttype) {
        suppressNode = (pos.getNodeName().toLowerCase().equals("xml"));
    }
    if (!suppressNode) {
        // Inserting next. NOTE that we force the node type; for
        // coalesced Text, this records CDATASections adjacent to
        // ordinary Text as Text.
        int nextindex = addNode(next, m_last_parent, m_last_kid, nexttype);
        m_last_kid = nextindex;
        if (ELEMENT_NODE == nexttype) {
            // start with no previous sib
            int attrIndex = NULL;
            // Process attributes _now_, rather than waiting.
            // Simpler control flow, makes NS cache available immediately.
            NamedNodeMap attrs = next.getAttributes();
            int attrsize = (attrs == null) ? 0 : attrs.getLength();
            if (attrsize > 0) {
                for (int i = 0; i < attrsize; ++i) {
                    // No need to force nodetype in this case;
                    // addNode() will take care of switching it from
                    // Attr to Namespace if necessary.
                    attrIndex = addNode(attrs.item(i), nextindex, attrIndex, NULL);
                    m_firstch.setElementAt(DTM.NULL, attrIndex);
                    // reserved xmlns: prefix
                    if (!m_processedFirstElement && "xmlns:xml".equals(attrs.item(i).getNodeName()))
                        m_processedFirstElement = true;
                }
            // Terminate list of attrs, and make sure they aren't
            // considered children of the element
            }
            // if attrs exist
            if (!m_processedFirstElement) {
                // The DOM might not have an explicit declaration for the
                // implicit "xml:" prefix, but the XPath data model
                // requires that this appear as a Namespace Node so we
                // have to synthesize one. You can think of this as
                // being a default attribute defined by the XML
                // Namespaces spec rather than by the DTD.
                attrIndex = addNode(new DOM2DTMdefaultNamespaceDeclarationNode((Element) next, "xml", NAMESPACE_DECL_NS, makeNodeHandle(((attrIndex == NULL) ? nextindex : attrIndex) + 1)), nextindex, attrIndex, NULL);
                m_firstch.setElementAt(DTM.NULL, attrIndex);
                m_processedFirstElement = true;
            }
            if (attrIndex != NULL)
                m_nextsib.setElementAt(DTM.NULL, attrIndex);
        }
    //if(ELEMENT_NODE)
    }
    // Advance the DOM cursor over contiguous text
    if (lastTextNode != null)
        next = lastTextNode;
    //}
    // Remember where we left off.
    m_pos = next;
    return true;
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node)

Example 50 with NamedNodeMap

use of org.w3c.dom.NamedNodeMap in project nokogiri by sparklemotion.

the class DOM2DTMExt method getUnparsedEntityURI.

/**
     * The getUnparsedEntityURI function returns the URI of the unparsed
     * entity with the specified name in the same document as the context
     * node (see [3.3 Unparsed Entities]). It returns the empty string if
     * there is no such entity.
     * <p>
     * XML processors may choose to use the System Identifier (if one
     * is provided) to resolve the entity, rather than the URI in the
     * Public Identifier. The details are dependent on the processor, and
     * we would have to support some form of plug-in resolver to handle
     * this properly. Currently, we simply return the System Identifier if
     * present, and hope that it a usable URI or that our caller can
     * map it to one.
     * TODO: Resolve Public Identifiers... or consider changing function name.
     * <p>
     * If we find a relative URI
     * reference, XML expects it to be resolved in terms of the base URI
     * of the document. The DOM doesn't do that for us, and it isn't
     * entirely clear whether that should be done here; currently that's
     * pushed up to a higher level of our application. (Note that DOM Level
     * 1 didn't store the document's base URI.)
     * TODO: Consider resolving Relative URIs.
     * <p>
     * (The DOM's statement that "An XML processor may choose to
     * completely expand entities before the structure model is passed
     * to the DOM" refers only to parsed entities, not unparsed, and hence
     * doesn't affect this function.)
     *
     * @param name A string containing the Entity Name of the unparsed
     * entity.
     *
     * @return String containing the URI of the Unparsed Entity, or an
     * empty string if no such entity exists.
     */
public String getUnparsedEntityURI(String name) {
    String url = "";
    Document doc = (m_root.getNodeType() == Node.DOCUMENT_NODE) ? (Document) m_root : m_root.getOwnerDocument();
    if (null != doc) {
        DocumentType doctype = doc.getDoctype();
        if (null != doctype) {
            NamedNodeMap entities = doctype.getEntities();
            if (null == entities)
                return url;
            Entity entity = (Entity) entities.getNamedItem(name);
            if (null == entity)
                return url;
            String notationName = entity.getNotationName();
            if (// then it's unparsed
            null != notationName) {
                // The draft says: "The XSLT processor may use the public
                // identifier to generate a URI for the entity instead of the URI
                // specified in the system identifier. If the XSLT processor does
                // not use the public identifier to generate the URI, it must use
                // the system identifier; if the system identifier is a relative
                // URI, it must be resolved into an absolute URI using the URI of
                // the resource containing the entity declaration as the base
                // URI [RFC2396]."
                // So I'm falling a bit short here.
                url = entity.getSystemId();
                if (null == url) {
                    url = entity.getPublicId();
                } else {
                // This should be resolved to an absolute URL, but that's hard
                // to do from here.
                }
            }
        }
    }
    return url;
}
Also used : Entity(org.w3c.dom.Entity) NamedNodeMap(org.w3c.dom.NamedNodeMap) DocumentType(org.w3c.dom.DocumentType) XMLString(org.apache.xml.utils.XMLString) Document(org.w3c.dom.Document)

Aggregations

NamedNodeMap (org.w3c.dom.NamedNodeMap)993 Node (org.w3c.dom.Node)690 NodeList (org.w3c.dom.NodeList)339 Attr (org.w3c.dom.Attr)295 Element (org.w3c.dom.Element)238 Document (org.w3c.dom.Document)154 ArrayList (java.util.ArrayList)92 HashMap (java.util.HashMap)91 DocumentBuilder (javax.xml.parsers.DocumentBuilder)59 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)58 IOException (java.io.IOException)53 SAXException (org.xml.sax.SAXException)41 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)40 List (java.util.List)36 Map (java.util.Map)33 File (java.io.File)27 InputStream (java.io.InputStream)26 CMNamedNodeMap (org.eclipse.wst.xml.core.internal.contentmodel.CMNamedNodeMap)25 DOMException (org.w3c.dom.DOMException)25 ByteArrayInputStream (java.io.ByteArrayInputStream)19