Search in sources :

Example 31 with DocumentType

use of org.w3c.dom.DocumentType in project robovm by robovm.

the class DOM2DTM 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)

Example 32 with DocumentType

use of org.w3c.dom.DocumentType in project robovm by robovm.

the class DOM3TreeWalker method isEntityReferneceWellFormed.

/**
     * Checks if an EntityRefernece node is well-formed, by checking it's node name.  Then depending
     * on whether it is referenced in Element content or in an Attr Node, checks if the EntityReference
     * references an unparsed entity or a external entity and if so throws raises the 
     * appropriate well-formedness error.  
     * 
     * @param data The contents of the comment node
     * @parent The parent of the EntityReference Node
     */
protected void isEntityReferneceWellFormed(EntityReference node) {
    // Is the EntityReference name a valid XML name
    if (!isXMLName(node.getNodeName(), fIsXMLVersion11)) {
        String msg = Utils.messages.createMessage(MsgKey.ER_WF_INVALID_CHARACTER_IN_NODE_NAME, new Object[] { "EntityReference", node.getNodeName() });
        if (fErrorHandler != null) {
            fErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_WF_INVALID_CHARACTER_IN_NODE_NAME, null, null, null));
        }
    }
    // determine the parent node
    Node parent = node.getParentNode();
    // Traverse the declared entities and check if the nodeName and namespaceURI
    // of the EntityReference matches an Entity.  If so, check the if the notationName
    // is not null, if so, report an error.
    DocumentType docType = node.getOwnerDocument().getDoctype();
    if (docType != null) {
        NamedNodeMap entities = docType.getEntities();
        for (int i = 0; i < entities.getLength(); i++) {
            Entity ent = (Entity) entities.item(i);
            String nodeName = node.getNodeName() == null ? "" : node.getNodeName();
            String nodeNamespaceURI = node.getNamespaceURI() == null ? "" : node.getNamespaceURI();
            String entName = ent.getNodeName() == null ? "" : ent.getNodeName();
            String entNamespaceURI = ent.getNamespaceURI() == null ? "" : ent.getNamespaceURI();
            // WFC: Parsed Entity
            if (parent.getNodeType() == Node.ELEMENT_NODE) {
                if (entNamespaceURI.equals(nodeNamespaceURI) && entName.equals(nodeName)) {
                    if (ent.getNotationName() != null) {
                        String msg = Utils.messages.createMessage(MsgKey.ER_WF_REF_TO_UNPARSED_ENT, new Object[] { node.getNodeName() });
                        if (fErrorHandler != null) {
                            fErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_WF_REF_TO_UNPARSED_ENT, null, null, null));
                        }
                    }
                }
            }
            // WFC: No External Entity References
            if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
                if (entNamespaceURI.equals(nodeNamespaceURI) && entName.equals(nodeName)) {
                    if (ent.getPublicId() != null || ent.getSystemId() != null || ent.getNotationName() != null) {
                        String msg = Utils.messages.createMessage(MsgKey.ER_WF_REF_TO_EXTERNAL_ENT, new Object[] { node.getNodeName() });
                        if (fErrorHandler != null) {
                            fErrorHandler.handleError(new DOMErrorImpl(DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_WF_REF_TO_EXTERNAL_ENT, null, null, null));
                        }
                    }
                }
            }
        //end if WFC: No External Entity References
        }
    }
}
Also used : Entity(org.w3c.dom.Entity) NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node) DocumentType(org.w3c.dom.DocumentType)

Example 33 with DocumentType

use of org.w3c.dom.DocumentType in project JMRI by JMRI.

the class XMLUtil method normalize.

/**
     * Try to normalize a document by removing nonsignificant whitespace.
     *
     * @see "#62006"
     */
private static Document normalize(Document orig) throws IOException {
    DocumentBuilder builder = null;
    DocumentBuilderFactory factory = getFactory(false, false);
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        //NOI18N
        throw new IOException("Cannot create parser satisfying configuration parameters: " + e, e);
    }
    DocumentType doctype = null;
    NodeList nl = orig.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i) instanceof DocumentType) {
            // We cannot import DocumentType's, so we need to manually copy it.
            doctype = (DocumentType) nl.item(i);
        }
    }
    Document doc;
    if (doctype != null) {
        doc = builder.getDOMImplementation().createDocument(orig.getDocumentElement().getNamespaceURI(), orig.getDocumentElement().getTagName(), builder.getDOMImplementation().createDocumentType(orig.getDoctype().getName(), orig.getDoctype().getPublicId(), orig.getDoctype().getSystemId()));
        // XXX what about entity decls inside the DOCTYPE?
        doc.removeChild(doc.getDocumentElement());
    } else {
        doc = builder.newDocument();
    }
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (!(node instanceof DocumentType)) {
            try {
                doc.appendChild(doc.importNode(node, true));
            } catch (DOMException x) {
                // Thrown in NB-Core-Build #2896 & 2898 inside GeneratedFilesHelper.applyBuildExtensions
                throw new IOException("Could not import or append " + node + " of " + node.getClass(), x);
            }
        }
    }
    doc.normalize();
    // NOI18N
    nl = doc.getElementsByTagName("*");
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        removeXmlBase(e);
        NodeList nl2 = e.getChildNodes();
        for (int j = 0; j < nl2.getLength(); j++) {
            Node n = nl2.item(j);
            if (n instanceof Text && ((Text) n).getNodeValue().trim().length() == 0) {
                e.removeChild(n);
                // since list is dynamic
                j--;
            }
        }
    }
    return doc;
}
Also used : DOMException(org.w3c.dom.DOMException) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) DocumentType(org.w3c.dom.DocumentType) Text(org.w3c.dom.Text) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) Document(org.w3c.dom.Document)

Example 34 with DocumentType

use of org.w3c.dom.DocumentType in project webservices-axiom by apache.

the class DOMReader method proceed.

@Override
public boolean proceed() throws StreamException {
    Node currentNode = this.currentNode;
    int state = this.state;
    loop: while (true) {
        switch(state) {
            case START:
                if (rootNode instanceof Document) {
                    currentNode = rootNode;
                }
                state = NOT_VISITED;
                break;
            case NOT_VISITED:
                if (currentNode == null) {
                    currentNode = rootNode;
                } else {
                    Node node = currentNode.getFirstChild();
                    if (node == null) {
                        state = VISITED;
                    } else {
                        currentNode = node;
                    }
                }
                break;
            case VISITED:
                if (currentNode == null || currentNode instanceof Document) {
                    throw new IllegalStateException();
                } else if (currentNode == rootNode) {
                    currentNode = null;
                } else {
                    Node node = currentNode.getNextSibling();
                    if (node == null) {
                        currentNode = currentNode.getParentNode();
                    } else {
                        currentNode = node;
                        state = NOT_VISITED;
                    }
                }
                break;
            default:
                throw new IllegalStateException();
        }
        int nodeType = currentNode == null ? Node.DOCUMENT_NODE : currentNode.getNodeType();
        if (state == VISITED) {
            // In the future, there may be other node types that generate events here
            switch(nodeType) {
                case Node.ELEMENT_NODE:
                    handler.endElement();
                    break loop;
                case Node.DOCUMENT_NODE:
                    handler.completed();
                    state = COMPLETE;
                    break loop;
            }
        } else {
            switch(nodeType) {
                case Node.DOCUMENT_NODE:
                    if (currentNode != null) {
                        Document document = (Document) currentNode;
                        if (dom3) {
                            handler.startDocument(document.getInputEncoding(), document.getXmlVersion(), document.getXmlEncoding(), document.getXmlStandalone());
                        } else {
                            handler.startDocument(null, "1.0", null, null);
                        }
                    } else {
                        handler.startFragment();
                    }
                    break loop;
                case Node.DOCUMENT_TYPE_NODE:
                    DocumentType docType = (DocumentType) currentNode;
                    handler.processDocumentTypeDeclaration(docType.getName(), docType.getPublicId(), docType.getSystemId(), docType.getInternalSubset());
                    break loop;
                case Node.ELEMENT_NODE:
                    Element element = (Element) currentNode;
                    String localName = element.getLocalName();
                    if (localName == null) {
                        // TODO
                        throw new UnsupportedOperationException();
                    } else {
                        handler.startElement(nullToEmptyString(element.getNamespaceURI()), localName, nullToEmptyString(element.getPrefix()));
                    }
                    NamedNodeMap attributes = element.getAttributes();
                    // TODO: we should not push all attributes at once
                    for (int length = attributes.getLength(), i = 0; i < length; i++) {
                        Attr attr = (Attr) attributes.item(i);
                        String attrLocalName = attr.getLocalName();
                        if (attrLocalName == null) {
                            handler.processAttribute(attr.getName(), attr.getValue(), "CDATA", attr.getSpecified());
                        } else {
                            String namespaceURI = attr.getNamespaceURI();
                            if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) {
                                handler.processNamespaceDeclaration(attrLocalName.equals(XMLConstants.XMLNS_ATTRIBUTE) ? "" : attrLocalName, attr.getValue());
                            } else {
                                handler.processAttribute(nullToEmptyString(namespaceURI), attrLocalName, nullToEmptyString(attr.getPrefix()), attr.getValue(), "CDATA", attr.getSpecified());
                            }
                        }
                    }
                    handler.attributesCompleted();
                    break loop;
                case Node.TEXT_NODE:
                    handler.processCharacterData(currentNode.getNodeValue(), dom3 && ((Text) currentNode).isElementContentWhitespace());
                    break loop;
                case Node.CDATA_SECTION_NODE:
                    handler.startCDATASection();
                    handler.processCharacterData(currentNode.getNodeValue(), false);
                    handler.endCDATASection();
                    break loop;
                case Node.COMMENT_NODE:
                    handler.startComment();
                    handler.processCharacterData(currentNode.getNodeValue(), false);
                    handler.endComment();
                    break loop;
                case Node.PROCESSING_INSTRUCTION_NODE:
                    ProcessingInstruction pi = (ProcessingInstruction) currentNode;
                    handler.startProcessingInstruction(pi.getTarget());
                    handler.processCharacterData(pi.getData(), false);
                    handler.endProcessingInstruction();
                    break loop;
                case Node.ENTITY_REFERENCE_NODE:
                    if (!expandEntityReferences) {
                        handler.processEntityReference(currentNode.getNodeName(), null);
                        state = VISITED;
                        break loop;
                    } else {
                        // No event has been generated, so loop again
                        break;
                    }
                default:
                    // TODO
                    throw new UnsupportedOperationException("Unsupported node type " + nodeType);
            }
        }
    }
    this.currentNode = currentNode;
    this.state = state;
    return state == COMPLETE;
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) DocumentType(org.w3c.dom.DocumentType) Document(org.w3c.dom.Document) Attr(org.w3c.dom.Attr) ProcessingInstruction(org.w3c.dom.ProcessingInstruction)

Example 35 with DocumentType

use of org.w3c.dom.DocumentType in project Payara by payara.

the class VerifierTest method getRuntimeSpecVersion.

/*
     *getRuntimeSpecVersion()
     *   return Float Spec-version
     */
public Float getRuntimeSpecVersion() {
    String docType = null;
    String versionStr = null;
    Float versionFloat = null;
    try {
        DocumentType dt = getVerifierContext().getRuntimeDocument().getDoctype();
        if (dt == null)
            return null;
        docType = dt.getPublicId();
        StringTokenizer st = new StringTokenizer(docType, "//");
        while (st.hasMoreElements()) {
            String tmp = st.nextToken();
            if (tmp.startsWith("DTD")) {
                // this is the string we are interested in
                StringTokenizer versionST = new StringTokenizer(tmp);
                while (versionST.hasMoreElements()) {
                    versionStr = versionST.nextToken();
                    try {
                        versionFloat = Float.valueOf(versionStr);
                    } catch (NumberFormatException nfe) {
                    // ignore, this is just the other info of the publicID
                    }
                }
            }
        }
        return versionFloat;
    } catch (Exception ex) {
        // ex.printStackTrace();
        return null;
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) DocumentType(org.w3c.dom.DocumentType)

Aggregations

DocumentType (org.w3c.dom.DocumentType)107 Document (org.w3c.dom.Document)68 DOMImplementation (org.w3c.dom.DOMImplementation)34 Node (org.w3c.dom.Node)21 DOMException (org.w3c.dom.DOMException)19 Element (org.w3c.dom.Element)16 NamedNodeMap (org.w3c.dom.NamedNodeMap)14 NodeList (org.w3c.dom.NodeList)12 ArrayList (java.util.ArrayList)10 IDOMDocument (org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument)8 Entity (org.w3c.dom.Entity)8 IOException (java.io.IOException)7 CMDocument (org.eclipse.wst.xml.core.internal.contentmodel.CMDocument)6 DocumentBuilder (javax.xml.parsers.DocumentBuilder)5 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 Transformer (javax.xml.transform.Transformer)4 TransformerFactory (javax.xml.transform.TransformerFactory)4 DOMSource (javax.xml.transform.dom.DOMSource)4 StreamResult (javax.xml.transform.stream.StreamResult)4 Attr (org.w3c.dom.Attr)4