Example usage for org.w3c.dom Document createElementNS

List of usage examples for org.w3c.dom Document createElementNS

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

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

protected Element createElementForFamilyLocal(Document doc, String namespace, String localName) {
    Element result = null;//from  w ww .j ava  2s.c o m
    if (namespace == null) {
        result = doc.createElementNS(null, localName);
    } else {
        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 . ja v a2  s  .  c o  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

/**
 * Creates an Element in the XML Signature specification namespace.
 *
 * @param doc the factory Document//from  w ww  .ja  va 2 s . c  o m
 * @param elementName the local name of the Element
 * @return the Element
 */
public static Element createElementInSignatureSpace(Document doc, String elementName) {
    if (doc == null) {
        throw new RuntimeException("Document is null");
    }

    if ((dsPrefix == null) || (dsPrefix.length() == 0)) {
        return doc.createElementNS(Constants.SignatureSpecNS, elementName);
    }
    return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName);
}

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

/**
 * Creates an Element in the XML Encryption specification namespace.
 *
 * @param doc the factory Document//from w  w w  .j  av a 2s . c o m
 * @param elementName the local name of the Element
 * @return the Element
 */
public static Element createElementInEncryptionSpace(Document doc, String elementName) {
    if (doc == null) {
        throw new RuntimeException("Document is null");
    }

    if ((xencPrefix == null) || (xencPrefix.length() == 0)) {
        return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName);
    }
    return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName);
}

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

/**
 * Method createDSctx/*from   w  w w  .  j a v  a  2s .com*/
 *
 * @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.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected Element getStructure(Document doc, LayoutStructure ls) {
    Element structure = null;//from www . jav  a2 s  .  com

    String type = ls.getType();

    if (ls.isChannel()) {
        final IPortletDefinition channelDef = this.portletDefinitionRegistry
                .getPortletDefinition(String.valueOf(ls.getChanId()));
        if (channelDef != null && channelApproved(channelDef.getApprovalDate())) {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(), channelDef,
                    ls.getLocale());
        } else {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(),
                    MissingPortletDefinition.INSTANCE, null);
        }
    } else {
        // create folder objects including dlm new types in cp namespace
        if (type != null && type.startsWith(Constants.NS)) {
            structure = doc.createElementNS(Constants.NS_URI, type);
        } else {
            structure = doc.createElement("folder");
        }
        structure.setAttribute("name", ls.getName());
        structure.setAttribute("type", (type != null ? type : "regular"));
    }

    structure.setAttribute("hidden", (ls.isHidden() ? "true" : "false"));
    structure.setAttribute("immutable", (ls.isImmutable() ? "true" : "false"));
    structure.setAttribute("unremovable", (ls.isUnremovable() ? "true" : "false"));
    if (localeAware) {
        structure.setAttribute("locale", ls.getLocale()); // for i18n by Shoji
    }

    /*
     * Parameters from up_layout_param are loaded slightly differently for
     * folders and channels. For folders all parameters are added as attributes
     * of the Element. For channels only those parameters with names starting
     * with the dlm namespace Constants.NS are added as attributes to the Element.
     * Others are added as child parameter Elements.
     */
    if (ls.getParameters() != null) {
        for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
            final StructureParameter sp = (StructureParameter) itr.next();
            String pName = sp.getName();

            if (!ls.isChannel()) { // Folder
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                } else {
                    structure.setAttribute(pName, sp.getValue());
                }
            } else // Channel
            {
                // if dealing with a dlm namespace param add as attribute
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                    itr.remove();
                } else {
                    /*
                     * do traditional override processing. some explanation is in
                     * order. The structure element was created by the
                     * ChannelDefinition and only contains parameter children if the
                     * definition had defined parameters. These are checked for each
                     * layout loaded parameter as found in LayoutStructure.parameters.
                     * If a name match is found then we need to see if overriding is
                     * allowed and if so we set the value on the child parameter
                     * element. At that point we are done with that version loaded
                     * from the layout so we remove it from the in-memory set of
                     * parameters that are being merged-in. Then, after all such have
                     * been checked against those added by the channel definition we
                     * add in any remaining as adhoc, unregulated parameters.
                     */
                    final NodeList nodeListParameters = structure.getElementsByTagName("parameter");
                    for (int j = 0; j < nodeListParameters.getLength(); j++) {
                        final Element parmElement = (Element) nodeListParameters.item(j);
                        final NamedNodeMap nm = parmElement.getAttributes();

                        final String nodeName = nm.getNamedItem("name").getNodeValue();
                        if (nodeName.equals(pName)) {
                            final Node override = nm.getNamedItem("override");
                            if (override != null && override.getNodeValue().equals("yes")) {
                                final Node valueNode = nm.getNamedItem("value");
                                valueNode.setNodeValue(sp.getValue());
                            }
                            itr.remove();
                            break; // found the corresponding one so skip the rest
                        }
                    }
                }
            }
        }
        // For channels, add any remaining parameter elements loaded with the
        // layout as adhoc, unregulated, parameter children that can be overridden.
        if (ls.isChannel()) {
            for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
                final StructureParameter sp = (StructureParameter) itr.next();
                final Element parameter = doc.createElement("parameter");
                parameter.setAttribute("name", sp.getName());
                parameter.setAttribute("value", sp.getValue());
                parameter.setAttribute("override", "yes");
                structure.appendChild(parameter);
            }
        }
    }
    // finish setting up elements based on loaded params
    final String origin = structure.getAttribute(Constants.ATT_ORIGIN);
    final String prefix = ls.isChannel() ? channelPrefix : folderPrefix;

    // if not null we are dealing with a node incorporated from another
    // layout and this node contains changes made by the user so handle
    // id swapping.
    if (!origin.equals("")) {
        structure.setAttributeNS(Constants.NS_URI, Constants.ATT_PLF_ID, prefix + ls.getStructId());
        structure.setAttribute("ID", origin);
    } else if (!ls.isChannel())
    // regular folder owned by this user, need to check if this is a
    // directive or ui element. If the latter then use traditional id
    // structure
    {
        if (type != null && type.startsWith(Constants.NS)) {
            structure.setAttribute("ID", Constants.DIRECTIVE_PREFIX + ls.getStructId());
        } else {
            structure.setAttribute("ID", folderPrefix + ls.getStructId());
        }
    } else {
        logger.debug("Adding identifier {}{}", folderPrefix, ls.getStructId());
        structure.setAttribute("ID", channelPrefix + ls.getStructId());
    }
    structure.setIdAttribute(Constants.ATT_ID, true);
    return structure;
}

From source file:org.apgrid.ninf.ng4.grpcinfo.impl.GrpcInfoHome.java

private MessageElement buildExecInfo(BufferedReader reader) throws IOException, ParseException {
    final Map definitions = LdifUtils.parse(reader);
    final String name = (String) definitions.get("GridRPC-Funcname"); // NgMDS2.--
    final String path = (String) definitions.get("GridRPC-Path"); // NgMDS2.EXE_PATH
    final String classInfoString = (String) definitions.get("GridRPC-Stub"); // NgMDS2.EXE_CLASSINFO
    if ((name == null) || (path == null) || (classInfoString == null)) {
        return null;
    }//w  ww  . j  a v a  2s . c o  m
    InputStream is = null;
    Document document = null;
    try {
        is = new ByteArrayInputStream(classInfoString.getBytes());
        document = XMLUtils.newDocument(is);
    } catch (ParserConfigurationException e) {
        logger.error("ParserConfigurationException in building execinfo");
        return null;
    } catch (SAXException e) {
        logger.error("SAXException in building execinfo");
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    is = null;
    if (document == null) {
        return null;
    }
    final Element execInfo = document.createElementNS("http://ninf.apgrid.org/ng4", "ng4:execInfo");
    execInfo.setAttribute("hostName", this.hostName); // NgMDS4.HOSTNAME
    execInfo.setAttribute("className", name); // NgMDS4.CLASS_NAME
    execInfo.setAttribute("execPath", path); // NgMDS4.EXE_PATH
    execInfo.appendChild(document.getDocumentElement());
    return new MessageElement(execInfo);
}

From source file:org.apgrid.ninf.ng5.grpcinfo.impl.GrpcInfoHome.java

private MessageElement buildExecInfo(BufferedReader reader) throws IOException {
    final StringBuffer buf = new StringBuffer();
    String line;//from w w w  .  j a v  a  2s .  com
    while ((line = reader.readLine()) != null) {
        if (line.length() != 0) {
            buf.append(line);
            buf.append("\n");
        }
    }
    final String classInfoString = buf.toString();
    if (classInfoString == null) {
        return null;
    }
    InputStream is = null;
    Document document = null;
    try {
        is = new ByteArrayInputStream(classInfoString.getBytes());
        document = XMLUtils.newDocument(is);
    } catch (ParserConfigurationException e) {
        logger.error("ParserConfigurationException in building execinfo");
        return null;
    } catch (SAXException e) {
        logger.error("SAXException in building execinfo");
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    is = null;
    if (document == null) {
        return null;
    }
    final Element execInfo = document.createElementNS("http://ninf.apgrid.org/ng5", "ng5:execInfo");
    execInfo.appendChild(document.getDocumentElement());
    return new MessageElement(execInfo);
}

From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java

/**
 * Sign a simple DOM document using the configured JSR 105 Provider
 *///from w w w . j a v  a2s.  c o m
@Test
public void simpleDocumentSign() throws Exception {

    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "src/test/resources/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("target/signature.xml");

    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    PublicKey publicKey = cert.getPublicKey();

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = fac.newReference("#12345", fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Instantiate the document to be signed
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //Build a sample document. It will look something like:
    //<!-- Comment before -->
    //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1" ID="12345">Some simple text
    //</apache:RootElement>
    //<!-- Comment after -->
    doc.appendChild(doc.createComment(" Comment before "));

    Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement");

    root.setAttributeNS(null, "ID", "12345");

    root.setAttributeNS(null, "attr1", "test1");
    root.setAttributeNS(null, "attr2", "test2");
    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:foo",
            "http://example.org/#foo");
    root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test");

    root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:apache",
            "http://www.apache.org/ns/#app1");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    // Create a DOMSignContext and specify the DSA PrivateKey and
    // location of the resulting XMLSignature's parent element
    DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement());

    // Create the XMLSignature (but don't sign it yet)
    KeyInfoFactory kif = fac.getKeyInfoFactory();

    X509Data kv = kif.newX509Data(Collections.singletonList(cert));

    // Create a KeyInfo and add the KeyValue to it
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);

    // TODO : Verify signature ?

    // output the resulting document
    FileOutputStream f = new FileOutputStream(signatureFile);
    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();

}

From source file:org.callimachusproject.xproc.DecodeTextStep.java

public void run() throws SaxonApiException {
    try {/*  w w w . j  a  v a2 s  .  c  o  m*/
        while (source.moreDocuments()) {
            String text = decodeText(source.read());

            Document doc = DocumentFactory.newInstance().newDocument();
            doc.setDocumentURI(doc.getBaseURI());
            Element data = doc.createElementNS(XPROC_STEP, DATA);
            data.setAttribute("content-type", contentType);
            data.appendChild(doc.createTextNode(text));
            doc.appendChild(data);
            result.write(runtime.getProcessor().newDocumentBuilder().wrap(doc));
        }
    } catch (ParserConfigurationException e) {
        throw XProcException.dynamicError(30, step.getNode(), e, e.getMessage());
    } catch (UnsupportedEncodingException uee) {
        throw XProcException.stepError(10, uee);
    } catch (DecoderException e) {
        throw XProcException.dynamicError(30, step.getNode(), e, e.getMessage());
    }
}