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.xml.security.utils.XMLUtils.java

/**
 * 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/*from   ww  w  .  j a va2 s.  com*/
 * @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()) + "\"");
}

From source file:org.asimba.wa.integrationtest.saml2.model.Response.java

/**
 * Requires the responseDocument to be already initialized, just adding another
 * Signature section to the existing documnet
 * @param signatureHelper//from   ww  w . ja  v  a  2 s . c o  m
 * @return
 */
public String getMessageWithSignedAssertion(SignatureHelper signatureHelper) {
    if (_responseDocument == null) {
        try {
            _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true);
        } catch (OAException | XMLStreamException e) {
            _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e);
            return null;
        }
    }

    KeyPair keypair = signatureHelper.getKeyPairFromKeystore();

    // Set signing context with PrivateKey and root of the Document
    Node localRoot = _assertion.getAssertionNode();
    signatureHelper.tagIdAttributes(localRoot.getOwnerDocument());

    DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), localRoot);

    // Get SignatureFactory for creating signatures in DOM:
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    Reference refAssertion = null;
    SignedInfo si = null;
    XMLSignature signature = null;

    try {
        // Create reference for "" -> Assertion in the document
        // SAML requires enveloped transform
        List<Transform> transformsList = new ArrayList<>();
        transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null));

        refAssertion = fac.newReference("#" + getAssertion().getId(),
                fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null);

        // Create SignedInfo (SAML2: Exclusive with or without comments is specified)
        // .. some selection here; nothing fancy, just trying to switch based on signing key format
        String sigMethod;
        String keyAlg = keypair.getPrivate().getAlgorithm();
        if (keyAlg.contains("RSA")) {
            sigMethod = SignatureMethod.RSA_SHA1;
        } else if (keyAlg.contains("DSA")) {
            sigMethod = SignatureMethod.DSA_SHA1;
        } else {
            _logger.error("Unknown signing key algorithm: {}", keyAlg);
            return null;
        }

        si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(sigMethod, null), Collections.singletonList(refAssertion));

        // Add KeyInfo to the document:
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        // .. get key from the generated keypair:
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

        signature = fac.newXMLSignature(si, ki);

        // before:
        _logger.info("Signing assertion in document");
        //         _logger.info("Document to sign:\n{}", XMLUtils.getStringFromDocument(localRoot.getOwnerDocument()));

        // Sign!
        signature.sign(dsc);

        return XMLUtils.getStringFromDocument(localRoot.getOwnerDocument());

    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        _logger.error("Could not create reference to signable content: {}", e.getMessage(), e);
        return null;
    } catch (KeyException e) {
        _logger.error("Could not establish key info: {}", e.getMessage(), e);
        return null;
    } catch (MarshalException | XMLSignatureException e) {
        _logger.error("Error signing document: {}", e.getMessage(), e);
        return null;
    } catch (OAException e) {
        _logger.error("Error creating string from XML document: {}", e.getMessage(), e);
        return null;
    }
}

From source file:org.automagic.deps.doctor.Utils.java

public static Node prettyFormat(Node node, int indentSize, boolean indentWithTabs) {

    if (indentSize < 1) {
        throw new IllegalArgumentException("Indentation size must be greater or equal to 1");
    }/*from   www.  j  av a2  s.  c om*/

    try {
        Source xmlInput = new DOMSource(node);

        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indentSize);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);

        String result = xmlOutput.getWriter().toString();

        if (indentWithTabs) {
            StringBuilder sb = new StringBuilder(result);
            Matcher matcher = INDENT_PATTERN.matcher(result);
            while (matcher.find()) {
                sb.setCharAt(matcher.start(), '\t');
            }
            result = sb.toString();
        }

        Document parse = DOC_BUILDER.get().parse(new ByteArrayInputStream(result.getBytes()));
        Node importNode = node.getOwnerDocument().importNode(parse.getDocumentElement(), true);

        return importNode;

    } catch (TransformerException | SAXException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.broad.igv.cbio.GeneNetwork.java

/**
 * Add the data specified by the score-types to our
 * network, using data from the tracks.//from   w ww. j  av a 2 s.  c  o  m
 * <p/>
 *
 * @param tracks
 * @param nodeAttributes
 */
public void annotate(List<Track> tracks, Collection<String> nodeAttributes) {

    Set<Node> nodes = this.vertexSet();
    String name;

    for (Node node : nodes) {
        name = getNodeKeyData(node, LABEL);

        ScoreData data = this.collectScoreData(name, tracks, nodeAttributes);

        //Don't add annotation if gene has no alteration?
        float relData = data.getPercentAltered();
        if (relData == 0 && !Globals.isTesting()) {
            continue;
        }

        for (String attr : nodeAttributes) {
            Element newData = node.getOwnerDocument().createElement("data");
            newData.setAttribute(KEY, attr);
            newData.setTextContent("" + data.get(attr));
            node.appendChild(newData);
        }

        //Set total
        Element newData = node.getOwnerDocument().createElement("data");
        newData.setAttribute(KEY, PERCENT_ALTERED);
        newData.setTextContent("" + data.getPercentAltered());

        node.appendChild(newData);
    }

    addSchema(Arrays.asList(PERCENT_ALTERED), "float", "node");
    addSchema(nodeAttributes, "float", "node");
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.AttributePreserveInsert.java

@Override
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }//from   w  w  w.  j  a va 2 s.c om
    Node node1 = nodeList1.get(0);
    Node node2 = nodeList2.get(0);
    NamedNodeMap attributes2 = node2.getAttributes();

    Comparator<Object> nameCompare = new Comparator<Object>() {
        @Override
        public int compare(Object arg0, Object arg1) {
            return ((Node) arg0).getNodeName().compareTo(((Node) arg1).getNodeName());
        }
    };
    Node[] tempNodes = {};
    tempNodes = exhaustedNodes.toArray(tempNodes);
    Arrays.sort(tempNodes, nameCompare);
    int length = attributes2.getLength();
    for (int j = 0; j < length; j++) {
        Node temp = attributes2.item(j);
        int pos = Arrays.binarySearch(tempNodes, temp, nameCompare);
        if (pos < 0) {
            Attr clone = (Attr) temp.cloneNode(true);
            ((Element) node1).setAttributeNode((Attr) node1.getOwnerDocument().importNode(clone, true));
        }
    }

    return null;
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.InsertChildrenOf.java

public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }/*from ww w .  j a va 2 s . c  o m*/
    Node node1 = nodeList1.get(0);
    Node node2 = nodeList2.get(0);
    NodeList list2 = node2.getChildNodes();
    for (int j = 0; j < list2.getLength(); j++) {
        node1.appendChild(node1.getOwnerDocument().importNode(list2.item(j).cloneNode(true), true));
    }

    Node[] response = new Node[nodeList2.size()];
    for (int j = 0; j < response.length; j++) {
        response[j] = nodeList2.get(j);
    }
    return response;
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.InsertItems.java

public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }/* w  ww.  j  av  a2s .co  m*/
    List<Node> usedNodes = new ArrayList<Node>();
    Node node1Parent = nodeList1.get(0).getParentNode();
    for (Node aNodeList2 : nodeList2) {
        Node tempNode = node1Parent.getOwnerDocument().importNode(aNodeList2.cloneNode(true), true);
        if (LOG.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer();
            sb.append("matching node for insertion: ");
            sb.append(tempNode.getNodeName());
            int attrLength = tempNode.getAttributes().getLength();
            for (int x = 0; x < attrLength; x++) {
                sb.append(" : (");
                sb.append(tempNode.getAttributes().item(x).getNodeName());
                sb.append("/");
                sb.append(tempNode.getAttributes().item(x).getNodeValue());
                sb.append(")");
            }
            LOG.debug(sb.toString());
        }
        if (LOG.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("inserting into parent: ");
            sb.append(node1Parent.getNodeName());
            int attrLength = node1Parent.getAttributes().getLength();
            for (int x = 0; x < attrLength; x++) {
                sb.append(" : (");
                sb.append(node1Parent.getAttributes().item(x).getNodeName());
                sb.append("/");
                sb.append(node1Parent.getAttributes().item(x).getNodeValue());
                sb.append(")");
            }
            LOG.debug(sb.toString());
        }
        node1Parent.appendChild(tempNode);
        usedNodes.add(tempNode);
    }

    Node[] response = { nodeList2.get(0).getParentNode() };
    return response;
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.NodeReplaceInsert.java

private List<Node> matchNodes(List<Node> exhaustedNodes, Node[] primaryNodes, ArrayList<Node> list) {
    List<Node> usedNodes = new ArrayList<Node>(20);
    Iterator<Node> itr = list.iterator();
    Node parentNode = primaryNodes[0].getParentNode();
    Document ownerDocument = parentNode.getOwnerDocument();
    while (itr.hasNext()) {
        Node node = itr.next();/*from  w w w.  j a  va  2  s . c  om*/
        if (Element.class.isAssignableFrom(node.getClass()) && !exhaustedNodesContains(exhaustedNodes, node)) {

            if (LOG.isDebugEnabled()) {
                StringBuffer sb = new StringBuffer();
                sb.append("matching node for replacement: ");
                sb.append(node.getNodeName());
                int attrLength = node.getAttributes().getLength();
                for (int j = 0; j < attrLength; j++) {
                    sb.append(" : (");
                    sb.append(node.getAttributes().item(j).getNodeName());
                    sb.append("/");
                    sb.append(node.getAttributes().item(j).getNodeValue());
                    sb.append(")");
                }
                LOG.debug(sb.toString());
            }
            if (!checkNode(usedNodes, primaryNodes, node)) {
                //simply append the node if all the above fails
                Node newNode = ownerDocument.importNode(node.cloneNode(true), true);
                parentNode.appendChild(newNode);
                usedNodes.add(node);
            }
        }
    }
    return usedNodes;
}

From source file:org.commonjava.maven.ext.core.impl.DistributionEnforcingManipulator.java

private Xpp3Dom getConfigXml(final Node node) throws ManipulationException {
    final String config = galleyWrapper.toXML(node.getOwnerDocument(), false).trim();

    try {// w w w .  j  a  va2s. c om
        return Xpp3DomBuilder.build(new StringReader(config));
    } catch (final XmlPullParserException | IOException e) {
        throw new ManipulationException(
                "Failed to re-parse plugin configuration into Xpp3Dom: %s\nConfig was:\n%s", e, e.getMessage(),
                config);
    }
}

From source file:org.cruxframework.crux.core.declarativeui.ViewParser.java

/**
 * Check if the target node is child from a rootDocument element or from a native XHTML element.
 * /*w  w  w. j a  v a2 s . co m*/
 * @param node
 * @return
 */
private boolean isHTMLChild(Node node) {
    Node parentNode = node.getParentNode();
    String namespaceURI = parentNode.getNamespaceURI();
    if (namespaceURI == null) {
        log.warn("The view [" + this.viewId
                + "] contains elements that is not bound to any namespace. It can cause errors while translating to an HTML page.");
    }
    if (node.getOwnerDocument().getDocumentElement().equals(parentNode)) {
        return true;
    }
    if (namespaceURI != null && namespaceURI.equals(XHTML_NAMESPACE) || isHtmlContainerWidget(parentNode)) {
        return true;
    }
    if (parentNode instanceof Element && namespaceURI != null && namespaceURI.equals(CRUX_CORE_NAMESPACE)
            && parentNode.getLocalName().equals(CRUX_CORE_SCREEN)) {
        return isHTMLChild(parentNode);
    }

    return false;
}