Example usage for org.w3c.dom Element getAttributes

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

Introduction

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

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

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

private Vector doEncryption(Document doc, SecretKey secretKey, KeyInfo keyInfo, Vector references)
        throws WSSecurityException {

    XMLCipher xmlCipher = null;//from   w w w.j  ava 2 s.  co m
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
    } catch (XMLEncryptionException e3) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
    }

    Vector encDataRef = new Vector();

    boolean cloneKeyInfo = false;
    for (int part = 0; part < references.size(); part++) {
        WSEncryptionPart encPart = (WSEncryptionPart) references.get(part);

        String idToEnc = encPart.getId();
        String elemName = encPart.getName();
        String nmSpace = encPart.getNamespace();
        String modifier = encPart.getEncModifier();
        //
        // Third step: get the data to encrypt.
        //
        Element body = null;
        if (idToEnc != null) {
            body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, WSConstants.WSU_NS);
            if (body == null) {
                body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, null);
            }
        } else {
            body = (Element) WSSecurityUtil.findElement(document, elemName, nmSpace);
        }
        if (body == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement",
                    new Object[] { "{" + nmSpace + "}" + elemName });
        }

        boolean content = modifier.equals("Content") ? true : false;
        String xencEncryptedDataId = wssConfig.getIdAllocator().createId("EncDataId-", body);
        encPart.setEncId(xencEncryptedDataId);

        cloneKeyInfo = true;

        if (keyInfo == null) {
            keyInfo = new KeyInfo(document);
            SecurityTokenReference secToken = new SecurityTokenReference(document);

            if (useKeyIdentifier && SecurityTokenReference.SAML_ID_URI.equals(customReferenceValue)) {
                secToken.setSAMLKeyIdentifier((encKeyIdDirectId ? "" : "#") + encKeyId);
            } else {
                Reference ref = new Reference(document);
                if (encKeyIdDirectId) {
                    ref.setURI(encKeyId);
                } else {
                    ref.setURI("#" + encKeyId);
                }
                if (encKeyValueType != null) {
                    ref.setValueType(encKeyValueType);
                }
                secToken.setReference(ref);
            }

            keyInfo.addUnknownElement(secToken.getElement());
            Element keyInfoElement = keyInfo.getElement();
            keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX,
                    WSConstants.SIG_NS);
        }
        //
        // Fourth step: encrypt data, and set necessary attributes in
        // xenc:EncryptedData
        //
        try {
            if (modifier.equals("Header")) {

                Element elem = doc.createElementNS(WSConstants.WSSE11_NS,
                        "wsse11:" + WSConstants.ENCRYPTED_HEADER);
                WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
                String wsuPrefix = WSSecurityUtil.setNamespace(elem, WSConstants.WSU_NS,
                        WSConstants.WSU_PREFIX);
                elem.setAttributeNS(WSConstants.WSU_NS, wsuPrefix + ":Id",
                        wssConfig.getIdAllocator().createId("EncHeader-", body));

                NamedNodeMap map = body.getAttributes();

                for (int i = 0; i < map.getLength(); i++) {
                    Attr attr = (Attr) map.item(i);
                    if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
                            || attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
                        String soapEnvPrefix = WSSecurityUtil.setNamespace(elem, attr.getNamespaceURI(),
                                WSConstants.DEFAULT_SOAP_PREFIX);
                        elem.setAttributeNS(attr.getNamespaceURI(), soapEnvPrefix + ":" + attr.getLocalName(),
                                attr.getValue());
                    }
                }

                xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
                EncryptedData encData = xmlCipher.getEncryptedData();
                encData.setId(xencEncryptedDataId);
                encData.setKeyInfo(keyInfo);
                xmlCipher.doFinal(doc, body, content);

                Element encDataElem = WSSecurityUtil.findElementById(document.getDocumentElement(),
                        xencEncryptedDataId, null);
                Node clone = encDataElem.cloneNode(true);
                elem.appendChild(clone);
                encDataElem.getParentNode().appendChild(elem);
                encDataElem.getParentNode().removeChild(encDataElem);
            } else {
                xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
                EncryptedData encData = xmlCipher.getEncryptedData();
                encData.setId(xencEncryptedDataId);
                encData.setKeyInfo(keyInfo);
                xmlCipher.doFinal(doc, body, content);
            }
            if (cloneKeyInfo) {
                keyInfo = new KeyInfo((Element) keyInfo.getElement().cloneNode(true), null);
            }
        } catch (Exception e2) {
            throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e2);
        }
        encDataRef.add("#" + xencEncryptedDataId);
    }
    return encDataRef;
}

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

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;/*from ww  w  .j  a  v a  2  s  .c o  m*/
    while (!(parent.getParentNode() instanceof Document)) {
        parent = parent.getParentNode();
        NamedNodeMap attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node 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) {
        NamedNodeMap attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node 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.WSSecSignatureBase.java

/**
 * Get the List of inclusive prefixes from the DOM Element argument 
 */// ww  w.  j av a  2  s .  co m
public List<String> getInclusivePrefixes(Element target, boolean excludeVisible) {
    List<String> result = new ArrayList<String>();
    Node parent = target;
    while (parent.getParentNode() != null && !(Node.DOCUMENT_NODE == parent.getParentNode().getNodeType())) {
        parent = parent.getParentNode();
        NamedNodeMap attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible) {
        NamedNodeMap attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    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.xml.security.c14n.implementations.Canonicalizer11.java

/**
 * Returns the Attr[]s to be output for the given element.
 * <br>//from  ww w  .  ja  v a 2s .c om
 * The code of this method is a copy of {@link #handleAttributes(Element,
 * NameSpaceSymbTable)},
 * whereas it takes into account that subtree-c14n is -- well -- 
 * subtree-based.
 * So if the element in question isRoot of c14n, it's parent is not in the
 * node set, as well as all other ancestors.
 *
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
        throws CanonicalizationException {
    if (!element.hasAttributes() && !firstCall) {
        return null;
    }
    // result will contain the attrs which have to be output
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                // It's not a namespace attr node. Add to the result and continue.
                result.add(attribute);
            } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
                // The default mapping for xml must not be output.
                Node n = ns.addMappingAndRender(NName, NValue, attribute);

                if (n != null) {
                    // Render the ns definition
                    result.add((Attr) n);
                    if (C14nHelper.namespaceIsRelative(attribute)) {
                        Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                        throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace", exArgs);
                    }
                }
            }
        }
    }

    if (firstCall) {
        // It is the first node of the subtree
        // Obtain all the namespaces defined in the parents, and added to the output.
        ns.getUnrenderedNodes(result);
        // output the attributes in the xml namespace.
        xmlattrStack.getXmlnsAttr(result);
        firstCall = false;
    }

    return result.iterator();
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

/**
 * Returns the Attr[]s to be output for the given element.
 * <br>/* www  .  j  a v a2 s.c  om*/
 * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a 
 * DOM which has been prepared using 
 * {@link org.apache.xml.security.utils.XMLUtils#circumventBug2650(
 * org.w3c.dom.Document)}.
 * 
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
        throws CanonicalizationException {
    // result will contain the attrs which have to be output
    xmlattrStack.push(ns.getLevel());
    boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                //A non namespace definition node.
                if (XML_LANG_URI.equals(NUri)) {
                    if (NName.equals("id")) {
                        if (isRealVisible) {
                            // treat xml:id like any other attribute 
                            // (emit it, but don't inherit it)
                            result.add(attribute);
                        }
                    } else {
                        xmlattrStack.addXmlnsAttr(attribute);
                    }
                } else if (isRealVisible) {
                    //The node is visible add the attribute to the list of output attributes.
                    result.add(attribute);
                }
            } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
                /* except omit namespace node with local name xml, which defines
                 * the xml prefix, if its string value is 
                 * http://www.w3.org/XML/1998/namespace.
                 */
                // add the prefix binding to the ns symb table.
                if (isVisible(attribute)) {
                    if (isRealVisible || !ns.removeMappingIfRender(NName)) {
                        // The xpath select this node output it if needed.
                        Node n = ns.addMappingAndRender(NName, NValue, attribute);
                        if (n != null) {
                            result.add((Attr) n);
                            if (C14nHelper.namespaceIsRelative(attribute)) {
                                Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                                throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace",
                                        exArgs);
                            }
                        }
                    }
                } else {
                    if (isRealVisible && !XMLNS.equals(NName)) {
                        ns.removeMapping(NName);
                    } else {
                        ns.addMapping(NName, NValue, attribute);
                    }
                }
            }
        }
    }

    if (isRealVisible) {
        //The element is visible, handle the xmlns definition        
        Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
        Node n = null;
        if (xmlns == null) {
            //No xmlns def just get the already defined.
            n = ns.getMapping(XMLNS);
        } else if (!isVisible(xmlns)) {
            //There is a definition but the xmlns is not selected by the xpath.
            //then xmlns=""
            n = ns.addMappingAndRender(XMLNS, "", nullNode);
        }
        //output the xmlns def if needed.
        if (n != null) {
            result.add((Attr) n);
        }
        //Float all xml:* attributes of the unselected parent elements to this one. 
        xmlattrStack.getXmlnsAttr(result);
        ns.getUnrenderedNodes(result);
    }

    return result.iterator();
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

protected void handleParent(Element e, NameSpaceSymbTable ns) {
    if (!e.hasAttributes() && e.getNamespaceURI() == null) {
        return;//ww w .j a  va 2s .  co  m
    }
    xmlattrStack.push(-1);
    NamedNodeMap attrs = e.getAttributes();
    int attrsLength = attrs.getLength();
    for (int i = 0; i < attrsLength; i++) {
        Attr attribute = (Attr) attrs.item(i);
        String NName = attribute.getLocalName();
        String NValue = attribute.getNodeValue();

        if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
            if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
                ns.addMapping(NName, NValue, attribute);
            }
        } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) {
            xmlattrStack.addXmlnsAttr(attribute);
        }
    }
    if (e.getNamespaceURI() != null) {
        String NName = e.getPrefix();
        String NValue = e.getNamespaceURI();
        String Name;
        if (NName == null || NName.equals("")) {
            NName = "xmlns";
            Name = "xmlns";
        } else {
            Name = "xmlns:" + NName;
        }
        Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
        n.setValue(NValue);
        ns.addMapping(NName, NValue, n);
    }
}

From source file:org.apache.xml.security.utils.IdResolver.java

public static int isElement(Element el, String id, Element[] els) {
    if (!el.hasAttributes()) {
        return 0;
    }/*w  w w .ja v a2s  .  c  o  m*/
    NamedNodeMap ns = el.getAttributes();
    int elementIndex = names.indexOf(el.getNamespaceURI());
    elementIndex = (elementIndex < 0) ? namesLength : elementIndex;
    for (int length = ns.getLength(), i = 0; i < length; i++) {
        Attr n = (Attr) ns.item(i);
        String s = n.getNamespaceURI();

        int index = s == null ? elementIndex : names.indexOf(n.getNamespaceURI());
        index = (index < 0) ? namesLength : index;
        String name = n.getLocalName();
        if (name == null) {
            name = n.getName();
        }
        if (name.length() > 2) {
            continue;
        }
        String value = n.getNodeValue();
        if (name.charAt(0) == 'I') {
            char ch = name.charAt(1);
            if (ch == 'd' && value.equals(id)) {
                els[index] = el;
                if (index == 0) {
                    return 1;
                }
            } else if (ch == 'D' && value.endsWith(id)) {
                if (index != 3) {
                    index = namesLength;
                }
                els[index] = el;
            }
        } else if ("id".equals(name) && value.equals(id)) {
            if (index != 2) {
                index = namesLength;
            }
            els[index] = el;
        }
    }
    //For an element namespace search for importants
    if ((elementIndex == 3) && (el.getAttribute("OriginalRequestID").equals(id)
            || el.getAttribute("RequestID").equals(id) || el.getAttribute("ResponseID").equals(id))) {
        els[3] = el;
    } else if ((elementIndex == 4) && (el.getAttribute("AssertionID").equals(id))) {
        els[4] = el;
    } else if ((elementIndex == 5)
            && (el.getAttribute("RequestID").equals(id) || el.getAttribute("ResponseID").equals(id))) {
        els[5] = el;
    }
    return 0;
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node// w ww.jav  a  2s  . c o m
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            Element element = (Element) node;
            if (!element.hasChildNodes()) {
                break;
            }
            if (element.hasAttributes()) {
                NamedNodeMap attributes = element.getAttributes();
                int attributesLength = attributes.getLength();

                for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {

                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element childElement = (Element) child;

                    for (int i = 0; i < attributesLength; i++) {
                        Attr currentAttr = (Attr) attributes.item(i);
                        if (!namespaceNs.equals(currentAttr.getNamespaceURI()))
                            continue;
                        if (childElement.hasAttributeNS(namespaceNs, currentAttr.getLocalName())) {
                            continue;
                        }
                        childElement.setAttributeNS(namespaceNs, currentAttr.getName(),
                                currentAttr.getNodeValue());
                    }
                }
            }
        case Node.ENTITY_REFERENCE_NODE:
            parent = node;
            sibling = node.getFirstChild();
            break;
        case Node.DOCUMENT_NODE:
            parent = node;
            sibling = node.getFirstChild();
            break;
        }
        while ((sibling == null) && (parent != null)) {
            sibling = parent.getNextSibling();
            parent = parent.getParentNode();
        }
        if (sibling == null) {
            return;
        }

        node = sibling;
        sibling = node.getNextSibling();
    } while (true);
}

From source file:org.apereo.portal.layout.dlm.FragmentDefinition.java

/**
 * This constructor is passed a dlm:fragment element from which this 
 * FragmentDefinition instance gathers its configuration information.
 * //from w  ww . ja v  a2  s .c  om
 * @param e An Element representing a single <dlm:fragment> in dlm.xml.
 * @throws Exception
 */
public FragmentDefinition(Element e) {
    NamedNodeMap atts = e.getAttributes();
    this.name = loadAttribute("name", atts, true, e);

    loadFromEelement(e);
}

From source file:org.apereo.portal.layout.dlm.FragmentDefinition.java

public void loadFromEelement(Element e) {
    final boolean REQUIRED = true;
    final boolean NOT_REQUIRED = false;

    NamedNodeMap atts = e.getAttributes();

    this.ownerID = loadAttribute("ownerID", atts, REQUIRED, e);
    this.defaultLayoutOwnerID = loadAttribute("defaultLayoutOwnerID", atts, NOT_REQUIRED, e);
    this.description = loadAttribute("description", atts, NOT_REQUIRED, e);

    String precedence = loadAttribute("precedence", atts, REQUIRED, e);
    try {//  ww  w  .ja va 2 s  .com
        this.precedence = Double.valueOf(precedence).doubleValue();
    } catch (NumberFormatException nfe) {
        throw new RuntimeException("Invalid format for precedence attribute " + "of <fragment> in\n'"
                + XmlUtilitiesImpl.toString(e), nfe);
    }

    // Audience Evaluators.
    // NB:  We're about to re-parse the complete set of evaluators, 
    // so we need to remove any that are already present.
    if (this.evaluators != null) {
        this.evaluators.clear();
    }
    loadAudienceEvaluators(e.getElementsByTagName("dlm:audience"));

}