Example usage for org.w3c.dom Element getPrefix

List of usage examples for org.w3c.dom Element getPrefix

Introduction

In this page you can find the example usage for org.w3c.dom Element getPrefix.

Prototype

public String getPrefix();

Source Link

Document

The namespace prefix of this node, or null if it is unspecified.

Usage

From source file:org.apache.cocoon.util.jxpath.DOMFactory.java

public String getNamespaceURI(Element element, String prefix) {
    Node tmp = element;/*w  w w.  ja  v a2  s. co  m*/
    String nsAttr = prefix == null ? "xmlns" : "xmlns:" + prefix;

    while (tmp != null && tmp.getNodeType() == Node.ELEMENT_NODE) {
        element = (Element) tmp;

        // First test element prefixes
        if (prefix == null) {
            if (element.getPrefix() == null) {
                return element.getNamespaceURI();
            }
        } else if (prefix.equals(element.getPrefix())) {
            return element.getNamespaceURI();
        }

        // Note: stupid DOM api returns "" when an attribute doesn't exist, so we use the Attr node.
        Attr nsAttrNode = ((Element) tmp).getAttributeNode(nsAttr);
        if (nsAttrNode != null) {
            return nsAttrNode.getValue();
        }
        tmp = tmp.getParentNode();
    }
    return null;
}

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

private Element replaceElement(Element lval, Element ptr, Element src, boolean keepSrcElement) {
    Document doc = ptr.getOwnerDocument();
    Node parent = ptr.getParentNode();
    if (keepSrcElement) {
        Element replacement = (Element) doc.importNode(src, true);
        parent.replaceChild(replacement, ptr);
        return (lval == ptr) ? replacement : lval;
    }/*from   ww w  .  j  a v  a2 s.c o m*/

    Element replacement = doc.createElementNS(ptr.getNamespaceURI(), ptr.getLocalName());
    if (ptr.getPrefix() != null) {
        replacement.setPrefix(ptr.getPrefix());
    }
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i)
        replacement.appendChild(doc.importNode(nl.item(i), true));
    NamedNodeMap attrs = src.getAttributes();
    for (int i = 0; i < attrs.getLength(); ++i) {
        Attr attr = (Attr) attrs.item(i);
        if (!attr.getName().startsWith("xmlns")) {
            replacement.setAttributeNodeNS((Attr) doc.importNode(attrs.item(i), true));
            // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually
            int colonIdx = attr.getValue().indexOf(":");
            if (colonIdx > 0) {
                String prefix = attr.getValue().substring(0, colonIdx);
                String attrValNs = src.lookupPrefix(prefix);
                if (attrValNs != null)
                    replacement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, attrValNs);
            }
        }
    }
    parent.replaceChild(replacement, ptr);
    DOMUtils.copyNSContext(ptr, replacement);

    return (lval == ptr) ? replacement : lval;
}

From source file:org.apache.ode.il.OMUtils.java

public static OMElement toOM(Element src, OMFactory omf, OMContainer parent) {
    OMElement omElement = parent == null ? omf.createOMElement(src.getLocalName(), null)
            : omf.createOMElement(src.getLocalName(), null, parent);
    if (src.getNamespaceURI() != null) {
        if (src.getPrefix() != null)
            omElement.setNamespace(omf.createOMNamespace(src.getNamespaceURI(), src.getPrefix()));
        else//  ww w  . ja  v  a2s.  c om
            omElement.declareDefaultNamespace(src.getNamespaceURI());
    }

    if (parent == null) {
        NSContext nscontext = DOMUtils.getMyNSContext(src);
        injectNamespaces(omElement, nscontext.toMap());
    } else {
        Map<String, String> nss = DOMUtils.getMyNamespaces(src);
        injectNamespaces(omElement, nss);
    }

    NamedNodeMap attrs = src.getAttributes();
    for (int i = 0; i < attrs.getLength(); ++i) {
        Attr attr = (Attr) attrs.item(i);
        if (attr.getLocalName().equals("xmlns")
                || (attr.getNamespaceURI() != null && attr.getNamespaceURI().equals(DOMUtils.NS_URI_XMLNS)))
            continue;
        OMNamespace attrOmNs = null;
        String attrNs = attr.getNamespaceURI();
        String attrPrefix = attr.getPrefix();
        if (attrNs != null)
            attrOmNs = omElement.findNamespace(attrNs, null);
        if (attrOmNs == null && attrPrefix != null)
            attrOmNs = omElement.findNamespace(null, attrPrefix);
        omElement.addAttribute(attr.getLocalName(), attr.getValue(), attrOmNs);
    }

    NodeList children = src.getChildNodes();
    for (int i = 0; i < children.getLength(); ++i) {
        Node n = children.item(i);

        switch (n.getNodeType()) {
        case Node.CDATA_SECTION_NODE:
            omElement.addChild(omf.createOMText(((CDATASection) n).getTextContent(), XMLStreamConstants.CDATA));
            break;
        case Node.TEXT_NODE:
            omElement.addChild(omf.createOMText(((Text) n).getTextContent(), XMLStreamConstants.CHARACTERS));
            break;
        case Node.ELEMENT_NODE:
            toOM((Element) n, omf, omElement);
            break;
        }

    }

    return omElement;
}

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

/**
 * Drop the attributes from an element, except possibly an <code>xmlns</code>
 * attribute that declares its namespace.
 * @param target the element whose attributes will be removed.
 * @param flag preserve namespace declaration
 *//* w w w.ja va 2 s  .  c  om*/
public static void removeAttributes(Element target, boolean flag) {
    if (!target.hasAttributes()) {
        return;
    }
    String prefix = target.getPrefix();
    NamedNodeMap nnm = target.getAttributes();
    Attr toPutBack = null;
    if (flag) {
        if (prefix == null) {
            toPutBack = target.getAttributeNodeNS(NS_URI_XMLNS, "xmlns");
        } else {
            toPutBack = target.getAttributeNodeNS(NS_URI_XMLNS, "xmlns:" + prefix);
        }

    }
    while (nnm.getLength() != 0) {
        target.removeAttributeNode((Attr) nnm.item(0));
    }
    if (toPutBack != null) {
        target.setAttributeNodeNS(toPutBack);
    }
}

From source file:org.apache.servicemix.jbi.runtime.impl.utils.DOMUtil.java

/**
 * Build a QName from the element name/*from w  w w  .j  a v a  2 s .  c om*/
 * @param el
 * @return
 */
public static QName getQName(Element el) {
    if (el == null) {
        return null;
    } else if (el.getNamespaceURI() == null) {
        return new QName(el.getNodeName());
    } else if (el.getPrefix() != null) {
        return new QName(el.getNamespaceURI(), el.getLocalName(), el.getPrefix());
    } else {
        return new QName(el.getNamespaceURI(), el.getLocalName());
    }
}

From source file:org.apache.sling.its.servlets.ItsImportServlet.java

/**
 * Store the global rule./*from  w  ww.java 2  s.c  om*/
 *
 * @param element
 *         an Element from the Document object.
 * @param resourceType
 *         resource type
 * @param itsEng
 *         the ITSEngine
 */
private void storeGlobalRule(final Element element, final String resourceType, final ITraversal itsEng) {
    if (StringUtils.isNotBlank(resourceType)) {
        String globalPath = SlingItsConstants.getGlobalRules().get(element.getLocalName()) + resourceType;
        if (element.getPrefix() != null) {
            globalPath += String.format("/%s(%d)", element.getLocalName(),
                    getCounter(globalPath + "/" + element.getLocalName()));
            element.setAttribute(SlingItsConstants.NODE_PREFIX, element.getPrefix());
        } else {
            globalPath += String.format("/%s(%d)", element.getNodeName(),
                    getCounter(globalPath + "/" + element.getNodeName()));
        }

        output(globalPath, null, null);
        if (element.getLocalName().equals("param")) {
            output(globalPath, null, element.getTextContent());
        } else if (element.getLocalName().equals(SlingItsConstants.ITS_LOCNOTE_RULE)
                && element.hasChildNodes()) {
            final Element locNoteElement = (Element) XmlNodeUtils.getChildNodeByLocalName(element,
                    SlingItsConstants.ITS_LOCNOTE);
            if (locNoteElement != null) {
                element.setAttribute(SlingItsConstants.ITS_NOTE, locNoteElement.getTextContent());
            }
        }
        setAttributes(element, globalPath);
    }
    skipChildren(element, itsEng);
}

From source file:org.apache.sling.its.servlets.ItsImportServlet.java

/**
 * Store the element and its attribute. The child node of global rules are
 * specially handled so they will not be traversed.
 *
 * @param path/* ww  w.  j ava  2s . c  o m*/
 *         the target path
 * @param resourceType
 *         the resourceType
 * @param doc
 *         the document
 * @param file
 *        the file.
 * @param isExternalDoc
 *         true if this is for storing global rules for external documents
 */
private void store(String path, final String resourceType, final Document doc, final File file,
        final boolean isExternalDoc) {
    final ITraversal itsEng = applyITSRules(doc, file, null, false);
    itsEng.startTraversal();
    Node node;
    while ((node = itsEng.nextNode()) != null) {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            final Element element = (Element) node;
            // Use !backTracking() to get to the elements only once
            // and to include the empty elements (for attributes).
            if (itsEng.backTracking()) {
                if (!SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) {
                    path = backTrack(path);
                }
            } else {
                if (element.isSameNode(doc.getDocumentElement()) && !isExternalDoc) {
                    path += "/" + element.getNodeName();
                    output(path, null, null);
                    setAttributes(element, path);
                } else if (SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) {
                    storeGlobalRule(element, resourceType, itsEng);
                } else if (!isExternalDoc
                        && !SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())
                        && !(element.getParentNode().getLocalName().equals(SlingItsConstants.ITS_RULES)
                                && element.getParentNode().getPrefix() != null)) {
                    if (element.getLocalName().equals(SlingItsConstants.ITS_RULES)
                            && element.getPrefix() != null) {
                        this.hasGlobalRules = true;
                    }
                    if (element.getPrefix() != null) {
                        path += String.format("/%s(%d)", element.getLocalName(),
                                getCounter(path + "/" + element.getLocalName()));
                        element.setAttribute(SlingItsConstants.NODE_PREFIX, element.getPrefix());
                    } else if (element.getNodeName().equals("link")
                            && StringUtils.endsWith(element.getAttribute("rel"), "-rules")) {
                        path += String.format("/%s(%d)", SlingItsConstants.ITS_RULES,
                                getCounter(path + "/" + SlingItsConstants.ITS_RULES));
                        final String prefix = StringUtils.substringBefore(element.getAttribute("rel"),
                                "-rules");
                        element.setAttribute(SlingItsConstants.NODE_PREFIX, prefix);
                        element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
                                SlingItsConstants.XMLNS + prefix, Namespaces.ITS_NS_URI);
                        element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:h",
                                Namespaces.HTML_NS_URI);
                        element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:jcr",
                                NamespaceRegistry.NAMESPACE_JCR);
                        this.hasGlobalRules = true;
                    } else {
                        path += String.format("/%s(%d)", element.getNodeName(),
                                getCounter(path + "/" + element.getNodeName()));
                    }
                    output(path, null, null);
                    setAttributes(element, path);
                    if (!element.hasChildNodes()) // Empty elements:
                    {
                        path = backTrack(path);
                    }
                }
            }
            break;
        case Node.TEXT_NODE:
            if (StringUtils.isNotBlank(node.getNodeValue()) && !isExternalDoc) {
                path += String.format("/%s(%d)", SlingItsConstants.TEXT_CONTENT_NODE,
                        getCounter(path + "/" + SlingItsConstants.TEXT_CONTENT_NODE));
                output(path, null, node.getNodeValue());
                path = backTrack(path);
            }
            break;
        default:
            break;
        }
    }
}

From source file:org.apache.ws.security.message.WSEncryptBody.java

private Document buildEmbedded(Document doc) throws WSSecurityException {
    doDebug = log.isDebugEnabled();//from  w w  w .  ja v  a2  s .  c  o  m

    long t0 = 0, t1 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }
    if (doDebug) {
        log.debug("Beginning Encryption embedded...");
    }

    /*
     * Second step: generate a symmetric key from the specified
     * key (password) for this algorithm, and set the cipher into
     * encryption mode.
     */
    this.encryptionKey = this.symmetricKey;
    if (this.encryptionKey == null) {
        if (embeddedKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied");
        }
        this.encryptionKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey);
    }

    KeyInfo keyInfo = null;
    if (this.keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) {
        keyInfo = new KeyInfo(doc);
        keyInfo.addKeyName(embeddedKeyName == null ? user : embeddedKeyName);
    } else if (this.keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
        /* This means that we want to embed a <wsse:SecurityTokenReference>
        * into keyInfo element.
        * If we need this functionality, this.secRef MUST be set before
        * calling the build(doc, crypto) method.
        * So if secRef is null then throw an exception.
        */
        if (this.securityTokenReference == null) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
                    "You must set keyInfo element, if the keyIdentifier " + "== EMBED_SECURITY_TOKEN_REF");
        } else {
            keyInfo = new KeyInfo(doc);
            Element tmpE = securityTokenReference.getElement();
            tmpE.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + tmpE.getPrefix(), tmpE.getNamespaceURI());
            keyInfo.addUnknownElement(securityTokenReference.getElement());
        }
    }

    Vector encDataRefs = doEncryption(doc, this.encryptionKey, keyInfo);

    /*
     * At this point data is encrypted with the symmetric key and can be
     * referenced via the above Id
     */

    /*
     * Now we need to setup the wsse:Security header block
     * 1) get (or create) the wsse:Security header block
     * 2) The last step sets up the reference list that pints to the encrypted
     *    data that was encrypted with this encrypted session key :-)
     */
    Element wsseSecurity = insertSecurityHeader(doc);

    Element tmpE = doc.createElement("temp");
    Element refList = createDataRefList(doc, tmpE, encDataRefs);
    WSSecurityUtil.prependChildElement(wsseSecurity, refList);

    if (tlog.isDebugEnabled()) {
        tlog.debug("EncryptBody embedded: symm-enc " + (t1 - t0));
    }
    return doc;
}

From source file:org.apache.ws.security.message.WSSecDKSign.java

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;/*w  w  w.java2  s  .  c om*/
    NamedNodeMap attributes;
    Node attribute;
    while (!(parent.getParentNode() instanceof Document)) {
        parent = parent.getParentNode();
        attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible == true) {
        attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

From source file:org.apache.ws.security.message.WSSecEncrypt.java

private Document buildEmbedded(Document doc, WSSecHeader secHeader) throws WSSecurityException {
    doDebug = log.isDebugEnabled();/*from  w  w w .  j a  v a 2  s .  c o  m*/

    if (doDebug) {
        log.debug("Beginning Encryption embedded...");
    }
    envelope = doc.getDocumentElement();
    envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS);

    //
    // Second step: generate a symmetric key from the specified key
    // (password) for this algorithm, and set the cipher into encryption
    // mode.
    //
    if (this.symmetricKey == null) {
        if (embeddedKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied");
        }
        this.symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey);
    }

    KeyInfo keyInfo = null;
    if (this.keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) {
        keyInfo = new KeyInfo(doc);
        keyInfo.addKeyName(embeddedKeyName == null ? user : embeddedKeyName);
    } else if (this.keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
        //
        // This means that we want to embed a <wsse:SecurityTokenReference>
        // into keyInfo element. If we need this functionality, this.secRef
        // MUST be set before calling the build(doc, crypto) method. So if
        // secRef is null then throw an exception.
        //
        if (this.securityTokenReference == null) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
                    "You must set keyInfo element, if the keyIdentifier == EMBED_SECURITY_TOKEN_REF");
        } else {
            keyInfo = new KeyInfo(doc);
            Element tmpE = securityTokenReference.getElement();
            tmpE.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + tmpE.getPrefix(), tmpE.getNamespaceURI());
            keyInfo.addUnknownElement(securityTokenReference.getElement());
        }
    }
    Element keyInfoElement = keyInfo.getElement();
    keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS);

    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);
    if (parts == null) {
        parts = new Vector();
        WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                soapConstants.getEnvelopeURI(), "Content");
        parts.add(encP);
    }
    Vector encDataRefs = doEncryption(doc, this.symmetricKey, keyInfo, parts);

    //
    // At this point data is encrypted with the symmetric key and can be
    // referenced via the above Id
    //

    //
    // Now we need to setup the wsse:Security header block 1) get (or
    // create) the wsse:Security header block 2) The last step sets up the
    // reference list that pints to the encrypted data
    //
    Element wsseSecurity = secHeader.getSecurityHeader();

    Element referenceList = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":ReferenceList");
    referenceList = createDataRefList(doc, referenceList, encDataRefs);
    WSSecurityUtil.prependChildElement(wsseSecurity, referenceList);

    return doc;
}