Java Code Examples for org.w3c.dom.Element#setAttributeNS()

The following examples show how to use org.w3c.dom.Element#setAttributeNS() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DOMKeyInfo.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void marshal(XMLStructure parent, XMLCryptoContext context)
    throws MarshalException
{
    if (parent == null) {
        throw new NullPointerException("parent is null");
    }
    if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
        throw new ClassCastException("parent must be of type DOMStructure");
    }

    Node pNode = ((javax.xml.crypto.dom.DOMStructure)parent).getNode();
    String dsPrefix = DOMUtils.getSignaturePrefix(context);
    Element kiElem = DOMUtils.createElement
        (DOMUtils.getOwnerDocument(pNode), "KeyInfo",
         XMLSignature.XMLNS, dsPrefix);
    if (dsPrefix == null || dsPrefix.length() == 0) {
        kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
                              "xmlns", XMLSignature.XMLNS);
    } else {
        kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
                              "xmlns:" + dsPrefix, XMLSignature.XMLNS);
    }
    marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext)context);
}
 
Example 2
Source File: SubjectConfirmationMarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
    SubjectConfirmation sc = (SubjectConfirmation) samlObject;

    if (sc.isSOAP11MustUnderstandXSBoolean() != null) {
        XMLHelper.marshallAttribute(SubjectConfirmation.SOAP11_MUST_UNDERSTAND_ATTR_NAME, 
                sc.isSOAP11MustUnderstandXSBoolean().toString(), domElement, false);
    }
    
    if (sc.getSOAP11Actor() != null) {
        XMLHelper.marshallAttribute(SubjectConfirmation.SOAP11_ACTOR_ATTR_NAME, 
                sc.getSOAP11Actor(), domElement, false);
    }
    
    if (sc.getMethod() != null) {
        domElement.setAttributeNS(null, SubjectConfirmation.METHOD_ATTRIB_NAME, sc.getMethod());
    }
}
 
Example 3
Source File: XMLHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds a namespace declaration (xmlns:) attribute to the given element.
 * 
 * @param domElement the element to add the attribute to
 * @param namespaceURI the URI of the namespace
 * @param prefix the prefix for the namespace
 */
public static void appendNamespaceDeclaration(Element domElement, String namespaceURI, String prefix) {
    String nsURI = DatatypeHelper.safeTrimOrNullString(namespaceURI);
    String nsPrefix = DatatypeHelper.safeTrimOrNullString(prefix);

    String attributeName;
    if (nsPrefix == null) {
        attributeName = XMLConstants.XMLNS_PREFIX;
    } else {
        attributeName = XMLConstants.XMLNS_PREFIX + ":" + nsPrefix;
    }

    String attributeValue;
    if (nsURI == null) {
        attributeValue = "";
    } else {
        attributeValue = nsURI;
    }

    domElement.setAttributeNS(XMLConstants.XMLNS_NS, attributeName, attributeValue);
}
 
Example 4
Source File: JexlIssueSamlClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Element createClaimsType(Document doc, URI claimTypeURI) {
    Element claimType = doc.createElementNS(STSConstants.IDT_NS_05_05, "ClaimType");
    claimType.setAttributeNS(null, "Uri", claimTypeURI.toString());
    claimType.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns", STSConstants.IDT_NS_05_05);

    return claimType;
}
 
Example 5
Source File: TokenTestUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void verifyToken(DoubleItPortType port) throws Exception {
    Client client = ClientProxy.getClient(port);
    Endpoint ep = client.getEndpoint();
    String id = (String)ep.get(SecurityConstants.TOKEN_ID);
    TokenStore store = (TokenStore)ep.getEndpointInfo().getProperty(TokenStore.class.getName());
    org.apache.cxf.ws.security.tokenstore.SecurityToken tok = store.getToken(id);
    assertNotNull(tok);
    STSClient sts = (STSClient)ep.get(SecurityConstants.STS_CLIENT);

    List<SecurityToken> validTokens = sts.validateSecurityToken(tok);
    assertTrue(validTokens != null && !validTokens.isEmpty());

    //mess with the token a bit to force it to fail to validate
    Element e = tok.getToken();
    Element e2 = DOMUtils.getFirstChildWithName(e, e.getNamespaceURI(), "Conditions");
    String nb = e2.getAttributeNS(null, "NotBefore");
    String noa = e2.getAttributeNS(null, "NotOnOrAfter");
    nb = "2010" + nb.substring(4);
    noa = "2010" + noa.substring(4);
    e2.setAttributeNS(null, "NotBefore", nb);
    e2.setAttributeNS(null, "NotOnOrAfter", noa);
    try {
        sts.validateSecurityToken(tok);
        fail("Failure expected on an invalid token");
    } catch (org.apache.cxf.ws.security.trust.TrustException ex) {
        // expected
    }
}
 
Example 6
Source File: FoxmlUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fixes DublinCore exported by Fedora Commons.
 * <p>The {@code schemaLocation} is removed.
 * <br>The namespace declaration is added to the root element.
 * @param dcRoot the root element of DC
 * @return the root element of DC
 */
public static Element fixFoxmlDc(Element dcRoot) {
    // remove xsi:schemaLocation attribute to make FOXML valid for Fedora ingest
    dcRoot.removeAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation");
    // optimize XML namespace declaration
    dcRoot.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
            XMLConstants.XMLNS_ATTRIBUTE + ":" + DcConstants.PREFIX_NS_PURL,
            DcConstants.NS_PURL);
    return dcRoot;
}
 
Example 7
Source File: STSServiceWsTrustImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public Element renewToken(Credential headerCredentials, Credential bodyCredentials, Element samlToken, int validity) throws TechnicalConnectorException {
   try {
      Element renewPayload = ConnectorXmlUtils.toElement(ConnectorIOUtils.convertStreamToString(ConnectorIOUtils.getResourceAsStream("/wstrust/renew.samlv11.template.xml")).getBytes());
      renewPayload.setAttributeNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "Context", IdGeneratorFactory.getIdGenerator("uuid").generateId());
      NodeList embeddedList = renewPayload.getElementsByTagNameNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Embedded");
      Element embedded = (Element)embeddedList.item(0);
      embedded.setAttributeNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "wsu:Id", "token-" + IdGeneratorFactory.getIdGenerator("uuid").generateId());
      Node samlTokenNode = renewPayload.getOwnerDocument().importNode(samlToken, true);
      embedded.appendChild(samlTokenNode);
      return this.processRequest(headerCredentials, bodyCredentials, renewPayload);
   } catch (SOAPException var9) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, var9, new Object[]{var9.getMessage()});
   }
}
 
Example 8
Source File: DIDLObject.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public void setOnElement(Element element) {
    element.setTextContent(toString());
    for (Property<DIDLAttribute> attr : attributes) {
        element.setAttributeNS(
                attr.getValue().getNamespaceURI(),
                attr.getValue().getPrefix() + ':' + attr.getDescriptorName(),
                attr.getValue().getValue());
    }
}
 
Example 9
Source File: DOMKeyValue.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void marshalPublicKey(Node parent, Document doc, String dsPrefix,
                      DOMCryptoContext context)
    throws MarshalException
{
    String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS);
    Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue",
                                                    XMLDSIG_11_XMLNS,
                                                    prefix);
    Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve",
                                                    XMLDSIG_11_XMLNS,
                                                    prefix);
    Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey",
                                                   XMLDSIG_11_XMLNS,
                                                   prefix);
    Object[] args = new Object[] { ecParams };
    String oid = getCurveOid(ecParams);
    if (oid == null) {
        throw new MarshalException("Invalid ECParameterSpec");
    }
    DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid);
    String qname = (prefix == null || prefix.length() == 0)
               ? "xmlns" : "xmlns:" + prefix;
    namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
                                  qname, XMLDSIG_11_XMLNS);
    ecKeyValueElem.appendChild(namedCurveElem);
    String encoded = Base64.encode(ecPublicKey);
    publicKeyElem.appendChild
        (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded));
    ecKeyValueElem.appendChild(publicKeyElem);
    parent.appendChild(ecKeyValueElem);
}
 
Example 10
Source File: ChangeNamespacePrefixProcessor.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void process(final Node aNode) {

    if (aNode instanceof Attr) {

        final Attr attribute = (Attr) aNode;
        final Element parentElement = attribute.getOwnerElement();

        if (isNamespaceDefinition(attribute)) {

            // Use the incredibly smooth DOM way to rename an attribute...
            parentElement.setAttributeNS(attribute.getNamespaceURI(), XMLNS + newPrefix, aNode.getNodeValue());
            parentElement.removeAttribute(XMLNS + oldPrefix);

        } else if (isElementReference(attribute)
                || isTypeAttributeWithPrefix(attribute)
                || isExtension(attribute)) {

            // Simply alter the value of the reference
            final String value = attribute.getValue();
            final String elementName = value.substring(value.indexOf(":") + 1);
            attribute.setValue(newPrefix + ":" + elementName);
        }
    }

    if (oldPrefix.equals(aNode.getPrefix())) {
        // Simply change the prefix to the new one.
        aNode.setPrefix(newPrefix);
    }
}
 
Example 11
Source File: ECKeyValueMarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException {
    ECKeyValue ec = (ECKeyValue) xmlObject;

    if (ec.getID() != null) {
        domElement.setAttributeNS(null, ECKeyValue.ID_ATTRIB_NAME, ec.getID());
        domElement.setIdAttributeNS(null, ECKeyValue.ID_ATTRIB_NAME, true);
    }
}
 
Example 12
Source File: DOMKeyValue.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
void marshalPublicKey(Node parent, Document doc, String dsPrefix,
                      DOMCryptoContext context)
    throws MarshalException
{
    String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS);
    Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue",
                                                    XMLDSIG_11_XMLNS,
                                                    prefix);
    Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve",
                                                    XMLDSIG_11_XMLNS,
                                                    prefix);
    Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey",
                                                   XMLDSIG_11_XMLNS,
                                                   prefix);
    Object[] args = new Object[] { ecParams };
    try {
        String oid = (String) getCurveName.invoke(null, args);
        DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid);
    } catch (IllegalAccessException iae) {
        throw new MarshalException(iae);
    } catch (InvocationTargetException ite) {
        throw new MarshalException(ite);
    }
    String qname = (prefix == null || prefix.length() == 0)
               ? "xmlns" : "xmlns:" + prefix;
    namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
                                  qname, XMLDSIG_11_XMLNS);
    ecKeyValueElem.appendChild(namedCurveElem);
    String encoded = Base64.encode(ecPublicKey);
    publicKeyElem.appendChild
        (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded));
    ecKeyValueElem.appendChild(publicKeyElem);
    parent.appendChild(ecKeyValueElem);
}
 
Example 13
Source File: XMLUtils.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method createDSctx
 *
 * @param doc
 * @param prefix
 * @param namespace
 * @return the element.
 */
public static Element createDSctx(Document doc, String prefix, String namespace) {
    if ((prefix == null) || (prefix.trim().length() == 0)) {
        throw new IllegalArgumentException("You must supply a prefix");
    }

    Element ctx = doc.createElementNS(null, "namespaceContext");

    ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace);

    return ctx;
}
 
Example 14
Source File: DOMKeyValue.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
void marshalPublicKey(Node parent, Document doc, String dsPrefix,
                      DOMCryptoContext context)
    throws MarshalException
{
    String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS);
    Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue",
                                                    XMLDSIG_11_XMLNS,
                                                    prefix);
    Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve",
                                                    XMLDSIG_11_XMLNS,
                                                    prefix);
    Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey",
                                                   XMLDSIG_11_XMLNS,
                                                   prefix);
    Object[] args = new Object[] { ecParams };
    try {
        String oid = (String) getCurveName.invoke(null, args);
        DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid);
    } catch (IllegalAccessException iae) {
        throw new MarshalException(iae);
    } catch (InvocationTargetException ite) {
        throw new MarshalException(ite);
    }
    String qname = (prefix == null || prefix.length() == 0)
               ? "xmlns" : "xmlns:" + prefix;
    namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
                                  qname, XMLDSIG_11_XMLNS);
    ecKeyValueElem.appendChild(namedCurveElem);
    String encoded = Base64.encode(ecPublicKey);
    publicKeyElem.appendChild
        (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded));
    ecKeyValueElem.appendChild(publicKeyElem);
    parent.appendChild(ecKeyValueElem);
}
 
Example 15
Source File: XMLCipher.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
Element toElement() {
    Element result =
        ElementProxy.createElementForFamily(
            contextDocument, EncryptionConstants.EncryptionSpecNS,
            EncryptionConstants._TAG_ENCRYPTEDDATA
        );

    if (null != super.getId()) {
        result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId());
    }
    if (null != super.getType()) {
        result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType());
    }
    if (null != super.getMimeType()) {
        result.setAttributeNS(
            null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType()
        );
    }
    if (null != super.getEncoding()) {
        result.setAttributeNS(
            null, EncryptionConstants._ATT_ENCODING, super.getEncoding()
        );
    }
    if (null != super.getEncryptionMethod()) {
        result.appendChild(
            ((EncryptionMethodImpl)super.getEncryptionMethod()).toElement()
        );
    }
    if (null != super.getKeyInfo()) {
        result.appendChild(super.getKeyInfo().getElement().cloneNode(true));
    }

    result.appendChild(((CipherDataImpl) super.getCipherData()).toElement());
    if (null != super.getEncryptionProperties()) {
        result.appendChild(((EncryptionPropertiesImpl)
            super.getEncryptionProperties()).toElement());
    }

    return result;
}
 
Example 16
Source File: DOMResultBuilder.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
public void startElement(QName element, XMLAttributes attributes,
        Augmentations augs) throws XNIException {
    Element elem;
    int attrCount = attributes.getLength();
    if (fDocumentImpl == null) {
        elem = fDocument.createElementNS(element.uri, element.rawname);
        for (int i = 0; i < attrCount; ++i) {
            attributes.getName(i, fAttributeQName);
            elem.setAttributeNS(fAttributeQName.uri, fAttributeQName.rawname, attributes.getValue(i));
        }
    }
    // If it's a Xerces DOM store type information for attributes, set idness, etc..
    else {
        elem = fDocumentImpl.createElementNS(element.uri, element.rawname, element.localpart);
        for (int i = 0; i < attrCount; ++i) {
            attributes.getName(i, fAttributeQName);
            AttrImpl attr = (AttrImpl) fDocumentImpl.createAttributeNS(fAttributeQName.uri,
                    fAttributeQName.rawname, fAttributeQName.localpart);
            attr.setValue(attributes.getValue(i));

            // write type information to this attribute
            AttributePSVI attrPSVI = (AttributePSVI) attributes.getAugmentations(i).getItem (Constants.ATTRIBUTE_PSVI);
            if (attrPSVI != null) {
                if (fStorePSVI) {
                    ((PSVIAttrNSImpl) attr).setPSVI(attrPSVI);
                }
                Object type = attrPSVI.getMemberTypeDefinition();
                if (type == null) {
                    type = attrPSVI.getTypeDefinition();
                    if (type != null) {
                        attr.setType (type);
                        if (((XSSimpleType) type).isIDType()) {
                            ((ElementImpl) elem).setIdAttributeNode (attr, true);
                        }
                    }
                }
                else {
                    attr.setType (type);
                    if (((XSSimpleType) type).isIDType()) {
                        ((ElementImpl) elem).setIdAttributeNode (attr, true);
                    }
                }
            }
            attr.setSpecified(attributes.isSpecified(i));
            elem.setAttributeNode(attr);
        }
    }
    append(elem);
    fCurrentNode = elem;
    if (fFragmentRoot == null) {
        fFragmentRoot = elem;
    }
}
 
Example 17
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Create a SecurityTokenReference to point to a SAML Assertion
 * @param doc The owner Document instance
 * @param id The Assertion ID
 * @param saml1 Whether the Assertion is a SAML1 or SAML2 Assertion
 * @param useDirectReferenceToAssertion whether to refer directly to the assertion or not
 * @return a SecurityTokenReference to a SAML Assertion
 */
private SecurityTokenReference createSTRForSamlAssertion(
    Document doc,
    String id,
    boolean saml1,
    boolean useDirectReferenceToAssertion
) {
    SecurityTokenReference secRefSaml = new SecurityTokenReference(doc);
    String secRefID = wssConfig.getIdAllocator().createSecureId("STR-", secRefSaml);
    secRefSaml.setID(secRefID);

    if (useDirectReferenceToAssertion) {
        org.apache.wss4j.common.token.Reference ref =
            new org.apache.wss4j.common.token.Reference(doc);
        ref.setURI("#" + id);
        if (saml1) {
            ref.setValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
            secRefSaml.addTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
        } else {
            secRefSaml.addTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
        }
        secRefSaml.setReference(ref);
    } else {
        Element keyId = doc.createElementNS(WSS4JConstants.WSSE_NS, "wsse:KeyIdentifier");
        String valueType = null;
        if (saml1) {
            valueType = WSS4JConstants.WSS_SAML_KI_VALUE_TYPE;
            secRefSaml.addTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
        } else {
            valueType = WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE;
            secRefSaml.addTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
        }
        keyId.setAttributeNS(
            null, "ValueType", valueType
        );
        keyId.appendChild(doc.createTextNode(id));
        Element elem = secRefSaml.getElement();
        elem.appendChild(keyId);
    }
    return secRefSaml;
}
 
Example 18
Source File: XMLCipher.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
Element toElement() {
    Element result =
        ElementProxy.createElementForFamily(
            contextDocument, EncryptionConstants.EncryptionSpecNS,
            EncryptionConstants._TAG_ENCRYPTEDKEY
        );

    if (null != super.getId()) {
        result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId());
    }
    if (null != super.getType()) {
        result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType());
    }
    if (null != super.getMimeType()) {
        result.setAttributeNS(
            null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType()
        );
    }
    if (null != super.getEncoding()) {
        result.setAttributeNS(null, Constants._ATT_ENCODING, super.getEncoding());
    }
    if (null != getRecipient()) {
        result.setAttributeNS(
            null, EncryptionConstants._ATT_RECIPIENT, getRecipient()
        );
    }
    if (null != super.getEncryptionMethod()) {
        result.appendChild(((EncryptionMethodImpl)
            super.getEncryptionMethod()).toElement());
    }
    if (null != super.getKeyInfo()) {
        result.appendChild(super.getKeyInfo().getElement().cloneNode(true));
    }
    result.appendChild(((CipherDataImpl) super.getCipherData()).toElement());
    if (null != super.getEncryptionProperties()) {
        result.appendChild(((EncryptionPropertiesImpl)
            super.getEncryptionProperties()).toElement());
    }
    if (referenceList != null && !referenceList.isEmpty()) {
        result.appendChild(((ReferenceListImpl)getReferenceList()).toElement());
    }
    if (null != carriedName) {
        Element element =
            ElementProxy.createElementForFamily(
                contextDocument,
                EncryptionConstants.EncryptionSpecNS,
                EncryptionConstants._TAG_CARRIEDKEYNAME
            );
        Node node = contextDocument.createTextNode(carriedName);
        element.appendChild(node);
        result.appendChild(element);
    }

    return result;
}
 
Example 19
Source File: XMLUtils.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
@SuppressWarnings("fallthrough")
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 :
        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);
}
 
Example 20
Source File: DOMUtils.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Sets an element's attribute (using DOM level 2) with the
 * specified value and namespace prefix.
 *
 * @param elem the element to set the attribute on
 * @param name the name of the attribute
 * @param value the attribute value. If null, no attribute is set.
 */
public static void setAttribute(Element elem, String name, String value) {
    if (value == null) {
        return;
    }
    elem.setAttributeNS(null, name, value);
}