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:com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI.java

@SuppressWarnings("unchecked")
public List<Node> selectList(Node contextNode, String xpath) {
    @SuppressWarnings("rawtypes")
    List nodes;//from  ww w  . ja v  a  2  s . c  o  m
    try {
        nodes = JXPathContext.newContext(contextNode).selectNodes(xpath);
        int i = 0;
        for (Object node : nodes) {
            if (node instanceof String) {
                node = contextNode.getOwnerDocument().createTextNode((String) node);
                nodes.set(i, node);
            }
            i++;
        }
    } catch (Exception e) {
        nodes = Collections.emptyList();
    }
    return (List<Node>) nodes;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.geosearch.GeosearchDataImportWriter.java

private Element generateField(GeosearchFieldVO field, Node document, String geomFieldName) {
    String column = field.getNameOnTable();
    String name = Utils.getFieldName(field);

    // uses the geometric field name as column name
    if ((geomFieldName != null) && geomFieldName.equals(column)) {
        column = name;/*from   w  w w . ja  v  a  2  s .c o m*/
    }

    Element fieldElement = document.getOwnerDocument().createElement("field");
    fieldElement.setAttribute("column", column);
    fieldElement.setAttribute("name", name);

    return fieldElement;
}

From source file:com.rest4j.generator.Generator.java

private void issueNode(List<Node> result, ModelNode node, boolean patch) {
    Node node1 = node.model.cloneNode(true);
    result.add(node1);/*  w  w  w  .  ja va  2s  .c  o  m*/
    if (patch)
        node1.getAttributes().setNamedItem(node1.getOwnerDocument().createAttribute("patch"));
}

From source file:org.guanxi.sp.engine.service.shibboleth.AuthConsumerServiceThread.java

/**
 * This prepares the response to the guard regarding the AA process.
 * //  ww w.  j a  v a  2s .c om
 * @param samlResponse  Used to generate the Guard request, this has been collected before this thread starts
 * @param guardSession  The string indicating the guard session to use
 * @param aaURL         The Attribute Authority URL which was just used to get the attributes
 * @param aaResponse    The response from talking to the Attribute Authority
 * @return              An EnvelopeDocument that must be sent to the Guard
 * @throws XmlException If there is a problem parsing the aaResponse
 */
private EnvelopeDocument prepareGuardRequest(ResponseType samlResponse, String guardSession, String aaURL,
        String aaResponse) throws XmlException {
    EnvelopeDocument soapEnvelopeDoc;
    Envelope soapEnvelope;

    soapEnvelopeDoc = EnvelopeDocument.Factory.parse(aaResponse);

    soapEnvelope = soapEnvelopeDoc.getEnvelope();

    // Before we send the SAML Response from the AA to the Guard, add the Guanxi SOAP header
    Header soapHeader = soapEnvelope.addNewHeader();
    Element gx = soapHeader.getDomNode().getOwnerDocument().createElementNS("urn:guanxi:sp",
            "GuanxiGuardSessionID");
    Node gxNode = soapHeader.getDomNode().appendChild(gx);
    org.w3c.dom.Text gxTextNode = soapHeader.getDomNode().getOwnerDocument().createTextNode(guardSession);
    gxNode.appendChild(gxTextNode);

    // Add the SAML Response from the IdP to the SOAP headers
    Header authHeader = soapEnvelope.addNewHeader();
    Element auth = authHeader.getDomNode().getOwnerDocument().createElementNS("urn:guanxi:sp", "AuthnFromIdP");
    auth.setAttribute("aa", aaURL);
    Node authNode = authHeader.getDomNode().appendChild(auth);
    authNode.appendChild(authNode.getOwnerDocument().importNode(samlResponse.getDomNode(), true));

    return soapEnvelopeDoc;
}

From source file:eionet.gdem.qa.QAResultPostProcessor.java

/**
 * Parses div nodes and adds warning node to result
 * @param divElements Div elements//  w  ww .  jav  a 2  s.co  m
 * @param warnMessage Warning message
 * @return true if feedbacktext class is found
 * @throws XmlException If an error occurs.
 */
private boolean parseDivNodes(NodeList divElements, String warnMessage) throws XmlException {
    boolean feedBackDivFound = false;
    try {
        for (int i = 0; divElements != null && i < divElements.getLength(); i++) {
            Node divNode = divElements.item(i);
            Node classNode = divNode.getAttributes().getNamedItem("class");

            if (classNode != null && classNode.getNodeValue().equalsIgnoreCase("feedbacktext")) {
                // found feedback div
                feedBackDivFound = true;

                Node firstChild = divNode.getFirstChild();
                Document doc = divNode.getOwnerDocument();

                Node warningNode = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(new InputSource(
                                new StringReader("<div class=\"error-msg\">" + warnMessage + "</div>")))
                        .getFirstChild();
                warningNode = doc.importNode(warningNode, true);
                if (firstChild == null) {
                    divNode.appendChild(warningNode);
                } else {
                    warningNode = divNode.insertBefore(warningNode, firstChild);
                }
                //
                break;
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error processing divNodes " + e);
    }
    return feedBackDivFound;
}

From source file:com.adaptris.util.XmlUtils.java

/**
 * Convenience method which enables a new Node to be added to a parent at a specified position, by specifying the Node to insert
 * before. Here is a sample of how to use:
 * /*from   w  ww .jav a2 s . co  m*/
 * <pre>
*  {@code 
 *
 *   // Example of how to insert a Node as the 3rd child of a parent
 *   Node p  = xmlUtils.getSingleNode("/mydoc/parent");
 *   Node c   = xmlUtils.getSingleNode("/mydoc/parent/child[4]");
 *   Node n = // Node creation code here;
 *   xmlUtils.insertNodeBefore(newNode, child, parent);
 *
 * }
 * </pre>
 * 
 * @param newNode the Node to be added
 * @param existingNode the Node to insert before
 * @param parent the parent Node
 * @throws Exception on error.
 */
public void insertNodeBefore(Node newNode, Node existingNode, Node parent) throws Exception {
    Document parentDoc = parent.getOwnerDocument();
    Document newDoc = newNode.getOwnerDocument();
    Node nodeToAdd = newNode;
    if (!parentDoc.equals(newDoc)) {
        nodeToAdd = parentDoc.importNode(newNode, true);
    }

    parent.insertBefore(nodeToAdd, existingNode);
}

From source file:com.adaptris.util.XmlUtils.java

/**
 * Convenience method which appends a new Node to the children of a parent
 *
 * @param newNode the Node to be added/*from   w w  w.j ava 2 s  .c  o m*/
 * @param parent the parent Node
 * @throws Exception on error.
 */
public void appendNode(Node newNode, Node parent) throws Exception {
    Document parentDoc = parent.getOwnerDocument();
    Document newDoc = newNode.getOwnerDocument();

    if (!parentDoc.equals(newDoc)) {
        newNode = parentDoc.importNode(newNode, true);
    }

    parent.appendChild(newNode);
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.geosearch.GeosearchDataImportWriter.java

private Element generateEntity(GeosearchTableVO geosearchTable, Node document) {
    Element entity = null;/*from w ww. j  av a2  s  .c  o  m*/

    Table table = geosearchTable.getTable();
    String dataSourceName = getDataSourceName(table.getSchema());
    String entityName = getEntityName(table);
    String query = getEntityQuery(geosearchTable);
    String keywords = geosearchTable.getKeywords();
    List<GeosearchFieldVO> fields = geosearchTable.getFields();

    // entity
    entity = document.getOwnerDocument().createElement("entity");
    entity.setAttribute("dataSource", dataSourceName);
    entity.setAttribute("name", entityName);
    entity.setAttribute("query", query);
    entity.setAttribute("transformer",
            PanelSettings.geosearchMaster.getFiles().getDataImport().getTransformer());
    if (!StringUtils.isEmpty(keywords)) {
        entity.setAttribute("keywords", keywords);
    }

    // fields
    String geomField = table.getGeomField();
    boolean hasDefinedField = false;
    for (GeosearchFieldVO field : fields) {
        if (field.isDefined()) {
            Element fieldElement = generateField(field, document, geomField);
            entity.appendChild(fieldElement);
            hasDefinedField = true;
        }
    }
    // adds the entity if it has defined fields
    if (!hasDefinedField) {
        entity = null;
    }
    return entity;
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java

/**
 * <p>//from www  .j  ava  2  s .  c o m
 * Implementation of MathML unification. In the given W3C DOM represented
 * XML document find all maths nodes (see
 * {@link DocumentParser#findMathMLNodes(org.w3c.dom.Document)}) and
 * remember links to operator elements and other elements in
 * {@link #nodesByDepth} data structure. Then substitute them gradualy for
 * series of formulae with leaf elements substituted for a special
 * unification representing symbol {@code &#x25CD;} (for Presentation
 * MathML, see {@link Constants#PMATHML_UNIFICATOR}) or {@code &#x25D0;}
 * (for Content MathML, see {@link Constants#CMATHML_UNIFICATOR}).
 * </p>
 * <p>
 * Resulting series of the original and unified MathML nodes is itself
 * encapsulated in a new element &lt;unified-math&gt; (see
 * {@link Constants#UNIFIED_MATHML_ROOT_ELEM}) in XML namespace
 * <code>http://mir.fi.muni.cz/mathml-unification/</code> (see
 * {@link Constants#UNIFIED_MATHML_NS}) and put to the place of the original
 * math element {@link Node} in the XML DOM representation the node is
 * attached to.
 * </p>
 *
 * @param mathNode W3C DOM XML document representation attached MathML node
 * to work on.
 * @param workInPlace If <code>true</code>, given <code>mathNode</code> will
 * be modified in place; if <code>false</code>, <code>mathNode</code> will
 * not be modified and series of modified nodes will be returned.
 * @param operatorUnification If <code>true</code> unify also operator
 * nodes, otherwise keep operator nodes intact.
 * @return <code>null</code> if <code>workInPlace</code> is
 * <code>false</code>; otherwise collection of unified versions of the
 * <code>mathNode</code> with key of the {@link HashMap} describing order
 * (level of unification) of elements in the collection.
 */
private HashMap<Integer, Node> unifyMathMLNodeImpl(Node mathNode, boolean operatorUnification,
        boolean workInPlace) {

    if (mathNode.getOwnerDocument() == null) {
        String msg = "The given node is not attached to any document.";
        if (mathNode.getNodeType() == Node.DOCUMENT_NODE) {
            msg = "The given node is document itself. Call with mathNode.getDocumentElement() instead.";
        }
        throw new IllegalArgumentException(msg);
    }

    nodesByDepth = new HashMap<>();

    Node unifiedMathNode = null;
    HashMap<Integer, Node> unifiedNodesList = null;
    Document unifiedMathDoc = null;

    if (workInPlace) {
        // New element encapsulating the series of unified formulae.
        unifiedMathNode = mathNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                UNIFIED_MATHML_ROOT_ELEM);
        mathNode.getParentNode().replaceChild(unifiedMathNode, mathNode);
        unifiedMathNode.appendChild(mathNode.cloneNode(true));
    } else {
        unifiedNodesList = new HashMap<>();
        // Create a new separate DOM to work over with imporeted clone of the node given by user
        unifiedMathDoc = DOMBuilder.createNewDocWithNodeClone(mathNode, true);
        mathNode = unifiedMathDoc.getDocumentElement();
    }

    // Parse XML subtree starting at mathNode and remember elements by their depth.
    rememberLevelsOfNodes(mathNode, operatorUnification);

    // Build series of formulae of level by level unified MathML.
    NodeLevel<Integer, Integer> level = new NodeLevel<>(getMaxMajorNodesLevel(), NUMOFMINORLEVELS);
    int levelAttrCounter = 0;
    Collection<Attr> maxLevelAttrs = new LinkedList<>();
    while (level.major > 0) {
        if (nodesByDepth.containsKey(level)) {
            if (unifyAtLevel(level)) {
                levelAttrCounter++;

                Node thisLevelMathNode = mathNode.cloneNode(true);
                Attr thisLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_LEVEL_ATTR);
                Attr maxLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_MAX_LEVEL_ATTR);
                maxLevelAttrs.add(maxLevelAttr);

                thisLevelAttr.setTextContent(String.valueOf(levelAttrCounter));

                ((Element) thisLevelMathNode).setAttributeNodeNS(thisLevelAttr);
                ((Element) thisLevelMathNode).setAttributeNodeNS(maxLevelAttr);

                if (workInPlace) {
                    unifiedMathNode.appendChild(thisLevelMathNode);
                } else {
                    // Create a new document for every node in the collection.
                    unifiedNodesList.put(levelAttrCounter,
                            DOMBuilder.cloneNodeToNewDoc(thisLevelMathNode, true));
                }
            }
        }
        level.minor--;
        if (level.minor <= 0) {
            level.major--;
            level.minor = NUMOFMINORLEVELS;
        }
    }
    for (Attr attr : maxLevelAttrs) {
        attr.setTextContent(String.valueOf((levelAttrCounter)));
    }

    if (workInPlace) {
        return null;
    } else {
        for (Node node : unifiedNodesList.values()) {
            Attr maxLevelAttr = (Attr) node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_MAX_LEVEL_ATTR);
            if (maxLevelAttr != null) {
                maxLevelAttr.setTextContent(String.valueOf((levelAttrCounter)));
            }
        }
        return unifiedNodesList;
    }

}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Transform into formatted XML.//from w  ww  .j  av  a2 s. c o m
 */
private String getFormattedXml(Node node) {
    Document document = node.getOwnerDocument().getImplementation().createDocument("", "fake", null);
    Element copy = (Element) document.importNode(node, true);
    document.importNode(node, false);
    document.removeChild(document.getDocumentElement());
    document.appendChild(copy);
    DOMImplementation domImpl = document.getImplementation();
    DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
    LSSerializer serializer = domImplLs.createLSSerializer();
    serializer.getDomConfig().setParameter("format-pretty-print", true);
    return serializer.writeToString(document);
}