Example usage for org.w3c.dom Node getOwnerDocument

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

Introduction

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

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Implementation for <code>String</code> :
 * outputs characters representing the value.
 *
 * @param parent The node getting the value
 * @param text   the value/*from   w w w  .ja  v  a2 s. c o m*/
 */
public static void valueOf(Node parent, String text) throws ProcessingException {
    if (text != null) {
        parent.appendChild(parent.getOwnerDocument().createTextNode(text));
    }
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Implementation for <code>org.w3c.dom.Node</code> :
 * converts the Node to a SAX event stream.
 *
 * @param parent The node getting the value
 * @param v the value/*from   w  ww  .  j a va 2s.c o m*/
 */
public static void valueOf(Node parent, Node v) throws ProcessingException {
    if (v != null) {
        parent.appendChild(parent.getOwnerDocument().importNode(v, true));
    }
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Implementation for <code>java.util.Map</code> :
 * For each entry an element is created with the childs key and value
 * Outputs the value and the key by calling {@link #valueOf(Node, Object)}
 * on each value and key of the Map./*from w  w w. jav  a2s.co m*/
 *
 * @param parent The node getting the value
 * @param v      the Map
 */
public static void valueOf(Node parent, Map v) throws ProcessingException {
    if (v != null) {
        Node mapNode = parent.getOwnerDocument().createElementNS(null, "java.util.map");
        parent.appendChild(mapNode);
        for (Iterator iter = v.entrySet().iterator(); iter.hasNext();) {
            Map.Entry me = (Map.Entry) iter.next();

            Node entryNode = mapNode.getOwnerDocument().createElementNS(null, "entry");
            mapNode.appendChild(entryNode);

            Node keyNode = entryNode.getOwnerDocument().createElementNS(null, "key");
            entryNode.appendChild(keyNode);
            valueOf(keyNode, me.getKey());

            Node valueNode = entryNode.getOwnerDocument().createElementNS(null, "value");
            entryNode.appendChild(valueNode);
            valueOf(valueNode, me.getValue());
        }
    }
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Use a path to select the first occurence of a node. The namespace
 * of a node is ignored!/* w ww .jav a  2s.  c o m*/
 * @param contextNode The node starting the search.
 * @param path        The path to search the node. The
 *                    contextNode is searched for a child named path[0],
 *                    this node is searched for a child named path[1]...
 * @param create      If a child with the corresponding name is not found
 *                    and create is set, this node will be created.
*/
public static Node getFirstNodeFromPath(Node contextNode, final String[] path, final boolean create) {
    if (contextNode == null || path == null || path.length == 0)
        return contextNode;
    // first test if the node exists
    Node item = getFirstNodeFromPath(contextNode, path, 0);
    if (item == null && create == true) {
        int i = 0;
        NodeList childs;
        boolean found;
        int m, l;
        while (contextNode != null && i < path.length) {
            childs = contextNode.getChildNodes();
            found = false;
            if (childs != null) {
                m = 0;
                l = childs.getLength();
                while (found == false && m < l) {
                    item = childs.item(m);
                    if (item.getNodeType() == Node.ELEMENT_NODE
                            && item.getLocalName().equals(path[i]) == true) {
                        found = true;
                        contextNode = item;
                    }
                    m++;
                }
            }
            if (found == false) {
                Element e = contextNode.getOwnerDocument().createElementNS(null, path[i]);
                contextNode.appendChild(e);
                contextNode = e;
            }
            i++;
        }
        item = contextNode;
    }
    return item;
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

/**
 * Change the namespace URI of a <code>node</code> and its children to
 * <code>newNamespaceUri</code> if that node is in the given <code>oldNamespaceUri</code>
 * namespace URI./* w ww .ja  va2s .  com*/
 * 
 * 
 * @param node {@link Node} to change namespace URI on.
 * @param oldNamespaceUri old namespace URI to change from.
 * @param newNamespaceUri new Namespace URI to change to.
 * @throws XPathExpressionException
 * @return the modified version of the passed in node.
 * @since GemFire 8.1
 */
static Node changeNamespace(final Node node, final String oldNamespaceUri, final String newNamespaceUri)
        throws XPathExpressionException {
    Node result = null;
    final NodeList nodes = query(node, "//*");
    for (int i = 0; i < nodes.getLength(); i++) {
        final Node element = nodes.item(i);
        if (element.getNamespaceURI() == null || element.getNamespaceURI().equals(oldNamespaceUri)) {
            Node renamed = node.getOwnerDocument().renameNode(element, newNamespaceUri, element.getNodeName());
            if (element == node) {
                result = renamed;
            }
        }
    }
    return result;
}

From source file:org.apache.hise.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *//*from   w w  w .java  2s.c  o  m*/
static public String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value = null;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}

From source file:org.apache.ode.bpel.engine.ProcessAndInstanceManagementImpl.java

/**
 * Fill in the <code>process-info</code> element of the transfer object.
 *
 * @param info/*  w ww .  j  a  v a2  s.  c  o m*/
 *            destination XMLBean
 * @param pconf
 *            process configuration object (from store)
 * @param proc
 *            source DAO object
 * @param custom
 *            used to customize the quantity of information produced in the
 *            info
 */
private void fillProcessInfo(TProcessInfo info, ProcessConf pconf, ProcessInfoCustomizer custom) {
    if (pconf == null)
        throw new IllegalArgumentException("Null pconf.");

    if (__log.isDebugEnabled())
        __log.debug("Filling process info for " + pconf.getProcessId());

    info.setPid(pconf.getProcessId().toString());
    // TODO: ACTIVE and RETIRED should be used separately.
    // Active process may be retired at the same time
    if (pconf.getState() == ProcessState.RETIRED) {
        info.setStatus(TProcessStatus.RETIRED);
    } else if (pconf.getState() == ProcessState.DISABLED) {
        info.setStatus(TProcessStatus.DISABLED);
    } else {
        info.setStatus(TProcessStatus.ACTIVE);
    }
    info.setVersion(pconf.getVersion());

    TDefinitionInfo definfo = info.addNewDefinitionInfo();
    definfo.setProcessName(pconf.getType());

    TDeploymentInfo depinfo = info.addNewDeploymentInfo();
    depinfo.setPackage(pconf.getPackage());
    if (__log.isDebugEnabled())
        __log.debug(" package name: " + depinfo.getPackage());
    depinfo.setDocument(pconf.getBpelDocument());
    depinfo.setDeployDate(toCalendar(pconf.getDeployDate()));
    depinfo.setDeployer(pconf.getDeployer());

    if (custom.includeDocumentLists()) {
        TProcessInfo.Documents docinfo = info.addNewDocuments();
        List<File> files = pconf.getFiles();
        if (files != null)
            genDocumentInfo(docinfo, files.toArray(new File[files.size()]), true);
        else if (__log.isDebugEnabled())
            __log.debug("fillProcessInfo: No files for " + pconf.getProcessId());
    }

    TProcessProperties properties = info.addNewProperties();
    if (custom.includeProcessProperties()) {
        for (Map.Entry<QName, Node> propEntry : pconf.getProcessProperties().entrySet()) {
            TProcessProperties.Property tprocProp = properties.addNewProperty();
            tprocProp.setName(
                    new QName(propEntry.getKey().getNamespaceURI(), propEntry.getKey().getLocalPart()));
            Node propNode = tprocProp.getDomNode();
            Document processInfoDoc = propNode.getOwnerDocument();
            Node node2append = processInfoDoc.importNode(propEntry.getValue(), true);
            propNode.appendChild(node2append);
        }
    }

    TEndpointReferences eprs = info.addNewEndpoints();
    OProcess oprocess = _server._engine.getOProcess(pconf.getProcessId());
    if (custom.includeEndpoints() && oprocess != null) {
        for (OPartnerLink oplink : oprocess.getAllPartnerLinks()) {
            if (oplink.hasPartnerRole() && oplink.initializePartnerRole) {
                // TODO: this is very uncool.
                EndpointReference pepr = _server._engine._activeProcesses.get(pconf.getProcessId())
                        .getInitialPartnerRoleEPR(oplink);

                if (pepr != null) {
                    TEndpointReferences.EndpointRef epr = eprs.addNewEndpointRef();
                    Document eprNodeDoc = epr.getDomNode().getOwnerDocument();
                    epr.getDomNode()
                            .appendChild(eprNodeDoc.importNode(pepr.toXML().getDocumentElement(), true));
                }
            }
        }
    }

    // TODO: add documents to the above data structure.
}

From source file:org.apache.ode.bpel.rtrep.v1.ASSIGN.java

/**
 * isInsert flag desginates this as an 'element' type insertion, which
 * requires insert the actual element value, rather than it's children
 *
 * @return//from w  ww  .ja va  2s .  c o  m
 * @throws FaultException
 */
private Node replaceContent(Node lvalue, Node lvaluePtr, String rvalue) throws FaultException {
    Document d = lvaluePtr.getOwnerDocument();

    if (__log.isDebugEnabled()) {
        __log.debug("lvaluePtr type " + lvaluePtr.getNodeType());
        __log.debug("lvaluePtr " + DOMUtils.domToString(lvaluePtr));
        __log.debug("lvalue " + lvalue);
        __log.debug("rvalue " + rvalue);
    }

    switch (lvaluePtr.getNodeType()) {
    case Node.ELEMENT_NODE:

        // Remove all the children.
        while (lvaluePtr.hasChildNodes())
            lvaluePtr.removeChild(lvaluePtr.getFirstChild());

        // Append a new text node.
        lvaluePtr.appendChild(d.createTextNode(rvalue));

        // If lvalue is a text, removing all lvaluePtr children had just removed it
        // so we need to rebuild it as a child of lvaluePtr
        if (lvalue instanceof Text)
            lvalue = lvaluePtr.getFirstChild();
        break;

    case Node.TEXT_NODE:

        Node newval = d.createTextNode(rvalue);
        // Replace ourselves .
        lvaluePtr.getParentNode().replaceChild(newval, lvaluePtr);

        // A little kludge, let our caller know that the root element has changed.
        // (used for assignment to a simple typed variable)
        if (lvalue.getNodeType() == Node.ELEMENT_NODE) {
            // No children, adding an empty text children to point to
            if (lvalue.getFirstChild() == null) {
                Text txt = lvalue.getOwnerDocument().createTextNode("");
                lvalue.appendChild(txt);
            }
            if (lvalue.getFirstChild().getNodeType() == Node.TEXT_NODE)
                lvalue = lvalue.getFirstChild();
        }
        if (lvalue.getNodeType() == Node.TEXT_NODE
                && ((Text) lvalue).getWholeText().equals(((Text) lvaluePtr).getWholeText()))
            lvalue = lvaluePtr = newval;
        break;

    case Node.ATTRIBUTE_NODE:

        ((Attr) lvaluePtr).setValue(rvalue);
        break;

    default:
        // This could occur if the expression language selects something
        // like
        // a PI or a CDATA.
        String msg = __msgs.msgInvalidLValue();
        if (__log.isDebugEnabled())
            __log.debug(lvaluePtr + ": " + msg);
        throw new FaultException(getOAsssign().getOwner().constants.qnSelectionFailure, msg);
    }

    return lvalue;
}

From source file:org.apache.ode.bpel.rtrep.v1.ASSIGN.java

private Node evalQuery(Node data, OMessageVarType.Part part, OExpression expression, EvaluationContext ec)
        throws FaultException {
    assert data != null;

    if (part != null) {
        QName partName = new QName(null, part.name);
        Node qualLVal = DOMUtils.findChildByName((Element) data, partName);
        if (part.type instanceof OElementVarType) {
            QName elName = ((OElementVarType) part.type).elementType;
            qualLVal = DOMUtils.findChildByName((Element) qualLVal, elName);
        } else if (part.type == null) {
            // Special case of header parts never referenced in the WSDL def
            if (qualLVal != null && qualLVal.getNodeType() == Node.ELEMENT_NODE
                    && ((Element) qualLVal).getAttribute("headerPart") != null
                    && DOMUtils.getTextContent(qualLVal) == null)
                qualLVal = DOMUtils.getFirstChildElement((Element) qualLVal);
            // The needed part isn't there, dynamically creating it
            if (qualLVal == null) {
                qualLVal = data.getOwnerDocument().createElementNS(null, part.name);
                ((Element) qualLVal).setAttribute("headerPart", "true");
                data.appendChild(qualLVal);
            }//from ww w  .  j ava 2  s. c  o  m
        }
        data = qualLVal;
    }

    if (expression != null) {
        // Neat little trick....
        data = ec.evaluateQuery(data, expression);
    }

    return data;
}

From source file:org.apache.ode.bpel.rtrep.v1.xpath20.JaxpVariableResolver.java

private Object getSimpleContent(Node simpleNode, QName type) {
    Document doc = (simpleNode instanceof Document) ? ((Document) simpleNode) : simpleNode.getOwnerDocument();
    String text = simpleNode.getTextContent();
    try {//w  ww .  j  a v  a 2  s.  c o m
        Object jobj = XSTypes.toJavaObject(type, text);
        if (jobj instanceof Calendar) {
            // Saxon 9.x prefers Dates over Calendars.
            return ((Calendar) jobj).getTime();
        } else if (jobj instanceof String) {
            // Saxon 9.x has a bug for which this is a workaround.
            return doc.createTextNode(jobj.toString());
        }
        return jobj;
    } catch (Exception e) {
        // Elegant way failed, trying brute force 
        try {
            return Integer.valueOf(text);
        } catch (NumberFormatException nfe) {
        }
        try {
            return Double.valueOf(text);
        } catch (NumberFormatException nfe) {
        }

        // Remember: always a node set
        if (simpleNode.getParentNode() != null)
            return simpleNode.getParentNode().getChildNodes();
        else {
            return doc.createTextNode(text);
        }
    }
}