Java Code Examples for org.w3c.dom.Node.getOwnerDocument()

The following are Jave code examples for showing how to use getOwnerDocument() of the org.w3c.dom.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: xmlrss   File: Dereferencer.java   Source Code and License Vote up 6 votes
/**
 * Dereference the given uri within the document of the given root element.
 * <p>
 * Currently this method only supports XPointer-ID-references and the special SignatureInfo-URI.
 *
 * @param uri  the uri to dereference
 * @param root the root node whose owner document is searched for dereferenciation
 * @return the dereferenced node
 * @throws RedactableXMLSignatureException if the given URI cannot be resolved or is not supported
 */
public static Node dereference(String uri, Node root) throws RedactableXMLSignatureException {
    if (uri == null || uri.length() == 0) {
        throw new RedactableXMLSignatureException("unsupported URI");
    } else if (isRootNodeXPointer(uri)) {
        return root;
    } else if (isIdXPointer(uri)) {
        Document doc = root.getOwnerDocument();
        String id = extractId(uri);
        Element element = doc.getElementById(id);
        if (element == null) {
            throw new RedactableXMLSignatureException("Cannot resolve element with ID " + id);
        }
        return element;
    } else if (isSignatureInfoURI(uri)) {
        return dereferenceSignatureInfo(root);
    }

    throw new RedactableXMLSignatureException("unsupported URI");
}
 
Example 2
Project: openjdk-jdk10   File: XMLUtils.java   Source Code and License Vote up 6 votes
/**
 * This method returns the first non-null owner document of the Nodes in this Set.
 * This method is necessary because it <I>always</I> returns a
 * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
 * if the {@link Node} is a {@link Document}.
 *
 * @param xpathNodeSet
 * @return the owner document
 */
public static Document getOwnerDocument(Set<Node> xpathNodeSet) {
    NullPointerException npe = null;
    for (Node node : xpathNodeSet) {
        int nodeType = node.getNodeType();
        if (nodeType == Node.DOCUMENT_NODE) {
            return (Document) node;
        }
        try {
            if (nodeType == Node.ATTRIBUTE_NODE) {
                return ((Attr)node).getOwnerElement().getOwnerDocument();
            }
            return node.getOwnerDocument();
        } catch (NullPointerException e) {
            npe = e;
        }
    }

    throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                   + " Original message was \""
                                   + (npe == null ? "" : npe.getMessage()) + "\"");
}
 
Example 3
Project: alvisnlp   File: XMLWriter.java   Source Code and License Vote up 6 votes
public static final NodeList features(ExpressionContext ctx) {
	NodeSet result = new NodeSet();
	Node node = ctx.getContextNode();
	Element elt = getElement(node);
	if (elt != null) {
		Document doc = node.getOwnerDocument();
		for (String name : elt.getFeatureKeys()) {
			for (String value : elt.getFeature(name)) {
				org.w3c.dom.Element e = doc.createElementNS(ALVISNLP_PROXY_NAMESPACE_URI, "feature");
				e.setAttribute("name", name);
				e.setAttribute("value", value);
				result.addElement(e);
			}
		}
	}
	return result;
}
 
Example 4
Project: openjdk-jdk10   File: XMLUtils.java   Source Code and License Vote up 5 votes
/**
 * This method returns the owner document of a particular node.
 * This method is necessary because it <I>always</I> returns a
 * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
 * if the {@link Node} is a {@link Document}.
 *
 * @param node
 * @return the owner document of the node
 */
public static Document getOwnerDocument(Node node) {
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        return (Document) node;
    }
    try {
        return node.getOwnerDocument();
    } catch (NullPointerException npe) {
        throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                       + " Original message was \""
                                       + npe.getMessage() + "\"");
    }
}
 
Example 5
Project: jetfuel   File: XmlArrayAdapter.java   Source Code and License Vote up 5 votes
/**
 * Formats the input array value as xml elements of a parent node.
 */
@SuppressWarnings("unchecked")
public Node format(Object value, Node parent) {
	if (value != null) {
		T[] arr = (T[]) value;
		Document document = parent.getOwnerDocument();
		for (int i = 0; i < arr.length; i++) {
			Element element = document.createElement(this.xmlName);
			this.componentAdapter.format(arr[i], element);
			parent.appendChild(element);
		}
	}
	return parent;
}
 
Example 6
Project: OpenJSharp   File: DomSerializer.java   Source Code and License Vote up 5 votes
/**
 * @param   node
 *      Nodes will be created and added under this object.
 */
public Dom2SaxAdapter(Node node)
{
    _node = node;
    _nodeStk.push(_node);

    if( node instanceof Document )
        this._document = (Document)node;
    else
        this._document = node.getOwnerDocument();
}
 
Example 7
Project: jetfuel   File: XmlElementAdapter.java   Source Code and License Vote up 5 votes
public Node format(Object value, Node parent) {

		if (this.xmlAdapter instanceof XmlAspect<?>) {
			return ((XmlAspect<?>) this.xmlAdapter).format(
					this.xmlName,
					value,
					parent);
		} else {
			Document document = parent.getOwnerDocument();
			Element element = document.createElement(this.xmlName);
			this.xmlAdapter.format(value, element);
			parent.appendChild(element);
			return element;
		}
	}
 
Example 8
Project: convertigo-engine   File: TwsCachedXPathAPI.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
public List<Node> selectList(Node contextNode, String xpath) {
	@SuppressWarnings("rawtypes")
	List nodes;
	try {
		nodes = JXPathContext.newContext(contextNode).selectNodes(xpath);
		int i = 0;
		for (Object node: nodes) {
			if (node instanceof Number) {
				Number num = (Number) node;
				if (num.intValue() == num.doubleValue()) {
					node = Integer.toString(num.intValue());
				} else {
					node = Double.toString(num.doubleValue());
				}
			} else if (node instanceof Boolean) {
				node = node.toString();
			}
			
			if (node instanceof String) {
				Document doc =  contextNode instanceof Document ? (Document)contextNode : contextNode.getOwnerDocument();
				node = doc.createTextNode((String) node);
				nodes.set(i, node);
			}
			i++;
		}
	} catch (Exception e) {
		nodes = Collections.emptyList();
	}
	return (List<Node>) nodes;
}
 
Example 9
Project: incubator-netbeans   File: RefreshDependencyVersions.java   Source Code and License Vote up 5 votes
private void addDependency(Node moduleDependencies, Dep inject, StringBuilder log) {
    Document nbprj = moduleDependencies.getOwnerDocument();
    Element nueDep = nbprj.createElement("dependency");
    moduleDependencies.appendChild(nueDep);

    Element nueCnb = nbprj.createElement("code-name-base");
    nueCnb.setTextContent(inject.getCodenameBase());
    nueDep.appendChild(nueCnb);
    log.append(inject.getCodenameBase());

    Element nueBuildPrerequisite = nbprj.createElement("build-prerequisite");
    nueDep.appendChild(nueBuildPrerequisite);

    Element nueCompileDep = nbprj.createElement("compile-dependency");
    nueDep.appendChild(nueCompileDep);
    
    Element nueRunDep = nbprj.createElement("run-dependency");
    nueDep.appendChild(nueRunDep);

    Element nueRelease = nbprj.createElement("release-version");
    String nue = checkReleaseVersion(inject.getRelease());
    nueRelease.setTextContent(nue);
    nueRunDep.appendChild(nueRelease);
    log.append('/').append(nue);

    if (inject.isImplementation()) {
        nueRunDep.appendChild(nbprj.createElement("implementation-version"));
        log.append(" = impl");
    } else {
        Element nueSpec = nbprj.createElement("specification-version");
        nue = checkSpecificationVersion(inject.getSpecification());
        nueSpec.setTextContent(nue);
        nueRunDep.appendChild(nueSpec);
        log.append(" >= " + nue);
    }
}
 
Example 10
Project: Equella   File: PropBagEx.java   Source Code and License Vote up 5 votes
/**
 * Gets the node for the given path.
 */
protected Node getNodeHelper(final String path, final boolean bCreate, final boolean bNew)
{
	if( path == null )
	{
		throw new IllegalArgumentException("Path must not be null");
	}

	// Split on the path identifier
	final List<String> pathComponents = DOMHelper.splitPath(path);

	Node node = m_elRoot;
	final Document doc = node.getOwnerDocument();

	final Iterator<String> iter = pathComponents.iterator();
	while( iter.hasNext() && node != null )
	{
		final String[] aszNodeName = new String[2];
		aszNodeName[0] = iter.next();

		// Extract the index if that exists
		final int nIndex = getIndexValue(aszNodeName);
		if( bNew && !iter.hasNext() )
		{
			final Node child = doc.createElement(aszNodeName[1]);
			node.appendChild(child);
			return child;
		}
		else
		{
			node = lookupNode(node, aszNodeName[1], nIndex, bCreate);
		}
	}

	return node;
}
 
Example 11
Project: openjdk-jdk10   File: RangeImpl.java   Source Code and License Vote up 5 votes
public void setStartAfter(Node refNode)
    throws RangeException
{
    if (fDocument.errorChecking) {
        if (fDetach) {
            throw new DOMException(
                    DOMException.INVALID_STATE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null));
        }
        if ( !hasLegalRootContainer(refNode) ||
                !isLegalContainedNode(refNode)) {
            throw new RangeExceptionImpl(
                    RangeException.INVALID_NODE_TYPE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_NODE_TYPE_ERR", null));
        }
        if ( fDocument != refNode.getOwnerDocument() && fDocument != refNode) {
            throw new DOMException(
                    DOMException.WRONG_DOCUMENT_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null));
        }
    }
    fStartContainer = refNode.getParentNode();
    int i = 0;
    for (Node n = refNode; n!=null; n = n.getPreviousSibling()) {
        i++;
    }
    fStartOffset = i;

    // If one boundary-point of a Range is set to have a root container
    // other
    // than the current one for the Range, the Range should be collapsed to
    // the new position.
    // The start position of a Range should never be after the end position.
    if (getCommonAncestorContainer() == null
            || (fStartContainer == fEndContainer && fEndOffset < fStartOffset)) {
        collapse(true);
    }
}
 
Example 12
Project: HL4A   File: XmlNode.java   Source Code and License Vote up 5 votes
void replaceWith(XmlNode other) {
    Node replacement = other.dom;
    if (replacement.getOwnerDocument() != this.dom.getOwnerDocument()) {
        replacement = this.dom.getOwnerDocument().importNode(replacement, true);
    }
    this.dom.getParentNode().replaceChild(replacement, this.dom);
}
 
Example 13
Project: openjdk-jdk10   File: RangeImpl.java   Source Code and License Vote up 5 votes
public void selectNodeContents(Node refNode)
    throws RangeException
{
    if (fDocument.errorChecking) {
        if( fDetach) {
            throw new DOMException(
                    DOMException.INVALID_STATE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null));
        }
        if ( !isLegalContainer(refNode)) {
            throw new RangeExceptionImpl(
                    RangeException.INVALID_NODE_TYPE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_NODE_TYPE_ERR", null));
        }
        if ( fDocument != refNode.getOwnerDocument() && fDocument != refNode) {
            throw new DOMException(
                    DOMException.WRONG_DOCUMENT_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null));
        }
    }
    fStartContainer = refNode;
    fEndContainer = refNode;
    Node first = refNode.getFirstChild();
    fStartOffset = 0;
    if (first == null) {
        fEndOffset = 0;
    } else {
        int i = 0;
        for (Node n = first; n!=null; n = n.getNextSibling()) {
            i++;
        }
        fEndOffset = i;
    }

}
 
Example 14
Project: OpenJSharp   File: XSAnnotationImpl.java   Source Code and License Vote up 5 votes
private synchronized void writeToDOM(Node target, short type) {
    Document futureOwner = (type == XSAnnotation.W3C_DOM_ELEMENT) ?
            target.getOwnerDocument() : (Document)target;
    DOMParser parser = fGrammar.getDOMParser();
    StringReader aReader = new StringReader(fData);
    InputSource aSource = new InputSource(aReader);
    try {
        parser.parse(aSource);
    }
    catch (SAXException e) {
        // this should never happen!
        // REVISIT:  what to do with this?; should really not
        // eat it...
    }
    catch (IOException i) {
        // ditto with above
    }
    Document aDocument = parser.getDocument();
    parser.dropDocumentReferences();
    Element annotation = aDocument.getDocumentElement();
    Node newElem = null;
    if (futureOwner instanceof CoreDocumentImpl) {
        newElem = futureOwner.adoptNode(annotation);
        // adoptNode will return null when the DOM implementations are not compatible.
        if (newElem == null) {
            newElem = futureOwner.importNode(annotation, true);
        }
    }
    else {
        newElem = futureOwner.importNode(annotation, true);
    }
    target.insertBefore(newElem, target.getFirstChild());
}
 
Example 15
Project: OpenJSharp   File: SAX2DOM.java   Source Code and License Vote up 5 votes
public SAX2DOM(Node root, Node nextSibling, boolean useServicesMechanism) throws ParserConfigurationException {
    _root = root;
    if (root instanceof Document) {
      _document = (Document)root;
    }
    else if (root != null) {
      _document = root.getOwnerDocument();
    }
    else {
      _document = createDocument(useServicesMechanism);
      _root = _document;
    }

    _nextSibling = nextSibling;
}
 
Example 16
Project: openjdk-jdk10   File: DOMSerializerImpl.java   Source Code and License Vote up 5 votes
private String _getXmlEncoding(Node node) {
    Document doc = (node.getNodeType() == Node.DOCUMENT_NODE)
            ? (Document) node : node.getOwnerDocument();
    if (doc != null) {
        try {
            return doc.getXmlEncoding();
        } // The VM ran out of memory or there was some other serious problem. Re-throw.
        catch (VirtualMachineError | ThreadDeath vme) {
            throw vme;
        } // Ignore all other exceptions and errors
        catch (Throwable t) {
        }
    }
    return null;
}
 
Example 17
Project: Tarski   File: Sax2Dom.java   Source Code and License Vote up 5 votes
public Sax2Dom(Node root) throws ParserConfigurationException {
  _root = root;
  if (root instanceof Document) {
    _document = (Document) root;
  } else if (root != null) {
    _document = root.getOwnerDocument();
  } else {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    _document = factory.newDocumentBuilder().newDocument();
    _root = _document;
  }
}
 
Example 18
Project: openjdk-jdk10   File: RangeImpl.java   Source Code and License Vote up 5 votes
public void setStart(Node refNode, int offset)
                     throws RangeException, DOMException
{
    if (fDocument.errorChecking) {
        if ( fDetach) {
            throw new DOMException(
                    DOMException.INVALID_STATE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null));
        }
        if ( !isLegalContainer(refNode)) {
            throw new RangeExceptionImpl(
                    RangeException.INVALID_NODE_TYPE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_NODE_TYPE_ERR", null));
        }
        if ( fDocument != refNode.getOwnerDocument() && fDocument != refNode) {
            throw new DOMException(
                    DOMException.WRONG_DOCUMENT_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null));
        }
    }

    checkIndex(refNode, offset);

    fStartContainer = refNode;
    fStartOffset = offset;

    // If one boundary-point of a Range is set to have a root container
    // other
    // than the current one for the Range, the Range should be collapsed to
    // the new position.
    // The start position of a Range should never be after the end position.
    if (getCommonAncestorContainer() == null
            || (fStartContainer == fEndContainer && fEndOffset < fStartOffset)) {
        collapse(true);
    }
}
 
Example 19
Project: javaide   File: ManifestMerger.java   Source Code and License Vote up 4 votes
private static int insertSourceMarker(@NonNull Node parent, @NonNull Node node,
        @NonNull File file, boolean after) {
    int insertCount = 0;
    Document doc = parent.getNodeType() ==
            Node.DOCUMENT_NODE ? (Document) parent : parent.getOwnerDocument();

    String comment;
    try {
        comment = SdkUtils.createPathComment(file, true);
    } catch (MalformedURLException e) {
        return insertCount;
    }

    Node prev = node.getPreviousSibling();
    String newline;
    if (prev != null && prev.getNodeType() == Node.TEXT_NODE) {
        // Duplicate indentation from previous line. Once we switch the merger
        // over to using the XmlPrettyPrinter, we won't need this.
        newline = prev.getNodeValue();
        int index = newline.lastIndexOf('\n');
        if (index != -1) {
            newline = newline.substring(index);
        }
    } else {
        newline = "\n";
    }

    if (after) {
        node = node.getNextSibling();
    }

    parent.insertBefore(doc.createComment(comment), node);
    insertCount++;

    // Can't add text nodes at the document level in Xerces, even though
    // it will happily parse these
    if (parent.getNodeType() != Node.DOCUMENT_NODE) {
        parent.insertBefore(doc.createTextNode(newline), node);
        insertCount++;
    }

    return insertCount;
}
 
Example 20
Project: incubator-netbeans   File: AttrImpl.java   Source Code and License Vote up 4 votes
/**
 * Get owner document or <code>null</code>
 */
public org.w3c.dom.Document getOwnerDocument() {
    Node parent = getOwnerElement();
    if (parent == null) return null;
    return parent.getOwnerDocument();
}