Example usage for org.w3c.dom Element setAttributeNS

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

Introduction

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

Prototype

public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java

String doSign() throws Exception {
    PrivateKey privateKey = kp.getPrivate();
    org.w3c.dom.Document doc = db.newDocument();
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");

    doc.appendChild(root);/*from   ww  w  .  j  a v  a2s.c  om*/
    root.appendChild(doc.createTextNode("Some simple text\n"));

    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc,
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);

    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    sig.addKeyInfo(kp.getPublic());
    sig.sign(privateKey);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return new String(bos.toByteArray());
}

From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java

String doSignWithCert() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = null;//from   w  ww .ja v a  2 s  .  c  o  m
    if (BASEDIR != null && !"".equals(BASEDIR)) {
        fis = new FileInputStream(BASEDIR + SEP + "data/test.jks");
    } else {
        fis = new FileInputStream("data/test.jks");
    }
    ks.load(fis, "changeit".toCharArray());
    PrivateKey privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    org.w3c.dom.Document doc = db.newDocument();
    X509Certificate signingCert = (X509Certificate) ks.getCertificate("mullan");
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");

    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, XMLSignature.ALGO_ID_SIGNATURE_DSA);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);

    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    sig.addKeyInfo(signingCert);
    sig.sign(privateKey);
    X509Certificate cert = sig.getKeyInfo().getX509Certificate();
    sig.checkSignatureValue(cert.getPublicKey());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return new String(bos.toByteArray());
}

From source file:org.apache.xml.security.test.signature.ECDSASignatureTest.java

private byte[] doSign() throws Exception {
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("ECDSA", ECDSA_JKS_PASSWORD.toCharArray());
    org.w3c.dom.Document doc = db.newDocument();
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");

    doc.appendChild(root);/*w  w w  .ja v  a 2  s.c  o m*/
    root.appendChild(doc.createTextNode("Some simple text\n"));

    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc,
            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);

    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    X509Certificate x509 = (X509Certificate) keyStore.getCertificate("ECDSA");
    sig.addKeyInfo(x509);
    sig.sign(privateKey);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return bos.toByteArray();
}

From source file:org.apache.xml.security.test.signature.XmlSecTest.java

private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception {
    Init.init();/*from w w w  .j  a  va  2  s. c o  m*/
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document testDocument = documentBuilder.newDocument();

    Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document");
    rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace");
    testDocument.appendChild(rootElement);
    Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child");
    childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace");
    childElement.appendChild(testDocument.createTextNode("hello world"));
    rootElement.appendChild(childElement);

    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    X509Certificate signingCert = null;
    if (cert) {
        // get key & self-signed certificate from keystore
        String fs = System.getProperty("file.separator");
        FileInputStream fis = new FileInputStream(BASEDIR + fs + "data" + fs + "test.jks");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(fis, "changeit".toCharArray());
        signingCert = (X509Certificate) ks.getCertificate("mullan");
        publicKey = signingCert.getPublicKey();
        privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    } else {
        KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();
    }

    XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA,
            Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);

    Element signatureElement = signature.getElement();
    rootElement.appendChild(signatureElement);

    Transforms transforms = new Transforms(testDocument);
    XPathContainer xpath = new XPathContainer(testDocument);
    xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
    xpath.setXPath("not(ancestor-or-self::ds:Signature)");
    transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns());
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1);

    if (cert) {
        signature.addKeyInfo(signingCert);
    } else {
        signature.addKeyInfo(publicKey);
    }

    Element nsElement = testDocument.createElementNS(null, "nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);

    signature.sign(privateKey);

    // TransformerFactory tf = TransformerFactory.newInstance();
    // Transformer t = tf.newTransformer();
    // t.transform(new DOMSource(testDocument), new StreamResult(System.out));

    NodeList signatureElems = XPathAPI.selectNodeList(testDocument, "//ds:Signature", nsElement);
    signatureElement = (Element) signatureElems.item(0);
    XMLSignature signatureToVerify = new XMLSignature(signatureElement, "");

    boolean signResult = signatureToVerify.checkSignatureValue(publicKey);

    assertTrue(signResult);
}

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

protected Element createElementForFamilyLocal(Document doc, String namespace, String localName) {
    Element result = null;
    if (namespace == null) {
        result = doc.createElementNS(null, localName);
    } else {/*from w  ww  . j a  v a2 s .c  o  m*/
        String baseName = this.getBaseNamespace();
        String prefix = ElementProxy.getDefaultPrefix(baseName);
        if ((prefix == null) || (prefix.length() == 0)) {
            result = doc.createElementNS(namespace, localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
        } else {
            result = doc.createElementNS(namespace, prefix + ":" + localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
        }
    }
    return result;
}

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

/**
 * This method creates an Element in a given namespace with a given localname.
 * It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether
 * a particular prefix is bound to that namespace.
 * <BR />/*from   w ww .  j  ava  2 s  .co m*/
 * This method was refactored out of the constructor.
 *
 * @param doc
 * @param namespace
 * @param localName
 * @return The element created.
 */
public static Element createElementForFamily(Document doc, String namespace, String localName) {
    Element result = null;
    String prefix = ElementProxy.getDefaultPrefix(namespace);

    if (namespace == null) {
        result = doc.createElementNS(null, localName);
    } else {
        if ((prefix == null) || (prefix.length() == 0)) {
            result = doc.createElementNS(namespace, localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
        } else {
            result = doc.createElementNS(namespace, prefix + ":" + localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
        }
    }

    return result;
}

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

/**
 * Method createDSctx/*from  ww  w . ja  v a 2 s.c  o m*/
 *
 * @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;
}

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

/**
 * This method spreads all namespace attributes in a DOM document to their
 * children. This is needed because the XML Signature XPath transform
 * must evaluate the XPath against all nodes in the input, even against
 * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are
 * not fully visible in the Xalan XPath model, so we have to do this by
 * hand in DOM spaces so that the nodes become visible in XPath space.
 *
 * @param doc//w ww  .j  a v a  2  s .c  o  m
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
public static void circumventBug2650(Document doc) {

    Element documentElement = doc.getDocumentElement();

    // if the document element has no xmlns definition, we add xmlns=""
    Attr xmlnsAttr = documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");

    if (xmlnsAttr == null) {
        documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
    }

    XMLUtils.circumventBug2650internal(doc);
}

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

/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node//w  w  w .j ava  2 s  .  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.DeleteManager.java

/**
   This method does the actual work of adding a delete directive and then
   recursively calling itself for any incoporated children that need to be
   deleted as well.//from   w  w w .  j  a  v a 2 s. co m
*/
private static void addDeleteDirective(Element compViewNode, String elementID, IPerson person, Document plf,
        Element delSet) throws PortalException {
    String ID = null;

    try {
        ID = getDLS().getNextStructDirectiveId(person);
    } catch (Exception e) {
        throw new PortalException("Exception encountered while " + "generating new delete node "
                + "Id for userId=" + person.getID(), e);
    }
    Element delete = plf.createElement(Constants.ELM_DELETE);
    delete.setAttribute(Constants.ATT_TYPE, Constants.ELM_DELETE);
    delete.setAttribute(Constants.ATT_ID, ID);
    delete.setAttributeNS(Constants.NS_URI, Constants.ATT_NAME, elementID);
    delSet.appendChild(delete);

    // now pass through children and add delete directives for those with
    // IDs indicating that they were incorporated
    Element child = (Element) compViewNode.getFirstChild();

    while (child != null) {
        String childID = child.getAttribute("ID");
        if (childID.startsWith(Constants.FRAGMENT_ID_USER_PREFIX))
            addDeleteDirective(child, childID, person, plf, delSet);
        child = (Element) child.getNextSibling();
    }
}