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.ode.il.epr.WSAEndpoint.java

public Document toXML() {
    // Wrapping/*  w ww .j a va 2  s .  c o m*/
    Document doc = DOMUtils.newDocument();
    Element serviceRef = doc.createElementNS(SERVICE_REF_QNAME.getNamespaceURI(),
            SERVICE_REF_QNAME.getLocalPart());
    doc.appendChild(serviceRef);
    serviceRef.appendChild(doc.importNode(_eprElmt, true));
    return _eprElmt.getOwnerDocument();
}

From source file:org.apache.ode.il.epr.WSAEndpoint.java

public void fromMap(Map eprMap) {
    Document doc = DOMUtils.newDocument();
    Element serviceRef = doc.createElementNS(SERVICE_REF_QNAME.getNamespaceURI(),
            SERVICE_REF_QNAME.getLocalPart());
    doc.appendChild(serviceRef);//  w  w  w. j  a  v  a 2 s  . com
    _eprElmt = doc.createElementNS(Namespaces.WS_ADDRESSING_NS, "EndpointReference");
    serviceRef.appendChild(_eprElmt);
    Element addrElmt = doc.createElementNS(Namespaces.WS_ADDRESSING_NS, "Address");
    addrElmt.setTextContent((String) eprMap.get(ADDRESS));
    if (eprMap.get(SESSION) != null) {
        Element sessElmt = doc.createElementNS(Namespaces.ODE_SESSION_NS, "session");
        sessElmt.setTextContent((String) eprMap.get(SESSION));
        _eprElmt.appendChild(sessElmt);
    }
    if (eprMap.get(SERVICE_QNAME) != null) {
        Element metadataElmt = doc.createElementNS(Namespaces.WS_ADDRESSING_NS, "Metadata");
        _eprElmt.appendChild(metadataElmt);
        Element serviceElmt = doc.createElementNS(Namespaces.WS_ADDRESSING_WSDL_NS, "ServiceName");
        metadataElmt.appendChild(serviceElmt);
        QName serviceQName = (QName) eprMap.get(SERVICE_QNAME);
        serviceElmt.setAttribute("xmlns:servicens", serviceQName.getNamespaceURI());
        serviceElmt.setTextContent("servicens:" + serviceQName.getLocalPart());
        serviceElmt.setAttribute("EndpointName", (String) eprMap.get(PORT_NAME));
    }
    _eprElmt.appendChild(addrElmt);
    if (__log.isDebugEnabled())
        __log.debug("Constructed a new WSAEndpoint: " + DOMUtils.domToString(_eprElmt));
}

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

@SuppressWarnings("unchecked")
public static Element toDOM(OMElement element, Document doc, boolean deepNS) {
    ///*from   w  w w  . j  a  v a 2s.  c om*/
    //  Fix regarding lost qnames on response of invoke activity:
    //    * copy an element including its prefix.
    //    * add all namespase attributes.
    //
    String domElementNsUri = element.getQName().getNamespaceURI();
    String domElementQName;
    if (element.getQName().getPrefix() == null || element.getQName().getPrefix().trim().length() == 0) {
        domElementQName = element.getQName().getLocalPart();
    } else {
        domElementQName = element.getQName().getPrefix() + ":" + element.getQName().getLocalPart();
    }
    if (__log.isTraceEnabled())
        __log.trace("toDOM: creating element with nsUri=" + domElementNsUri + " qname=" + domElementQName
                + " from omElement, name=" + element.getLocalName());

    final Element domElement = doc.createElementNS(domElementNsUri, domElementQName);

    if (deepNS) {
        NSContext nscontext = new NSContext();
        buildNScontext(nscontext, element);
        DOMUtils.injectNamespacesWithAllPrefixes(domElement, nscontext);
    } else {
        if (element.getAllDeclaredNamespaces() != null) {
            for (Iterator<OMNamespace> i = element.getAllDeclaredNamespaces(); i.hasNext();) {
                OMNamespace omns = i.next();
                if (omns.getPrefix().equals(""))
                    domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns",
                            omns.getNamespaceURI() == null ? "" : omns.getNamespaceURI());
                else
                    domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + omns.getPrefix(),
                            omns.getNamespaceURI());
            }

        }
    }
    if (__log.isTraceEnabled())
        __log.trace("toDOM: created root element (deepNS=" + deepNS + "): " + DOMUtils.domToString(domElement));

    for (Iterator i = element.getAllAttributes(); i.hasNext();) {
        final OMAttribute attr = (OMAttribute) i.next();
        Attr newAttr;
        if (attr.getNamespace() != null)
            newAttr = doc.createAttributeNS(attr.getNamespace().getNamespaceURI(), attr.getLocalName());
        else
            newAttr = doc.createAttributeNS(null, attr.getLocalName());

        newAttr.appendChild(doc.createTextNode(attr.getAttributeValue()));
        domElement.setAttributeNodeNS(newAttr);

        // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually...
        int colonIdx = attr.getAttributeValue().indexOf(":");
        if (colonIdx > 0) {
            OMNamespace attrValNs = element.findNamespaceURI(attr.getAttributeValue().substring(0, colonIdx));
            if (attrValNs != null)
                domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + attrValNs.getPrefix(),
                        attrValNs.getNamespaceURI());
        }
    }

    for (Iterator<OMNode> i = element.getChildren(); i.hasNext();) {
        OMNode omn = i.next();

        switch (omn.getType()) {
        case OMNode.CDATA_SECTION_NODE:
            domElement.appendChild(doc.createCDATASection(((OMText) omn).getText()));
            break;
        case OMNode.TEXT_NODE:
            domElement.appendChild(doc.createTextNode(((OMText) omn).getText()));
            break;
        case OMNode.ELEMENT_NODE:
            domElement.appendChild(toDOM((OMElement) omn, doc, false));
            break;
        }

    }

    return domElement;

}

From source file:org.apache.ode.jbi.OdeSUManager.java

/**
 * Generate those lame XML result strings that JBI requires. Oh did I mention
 * how lame this is? If not, let me remind the reader: this is just about the
 * lamest "clever idea" I have ever seen.
 *
 * @param task//from   ww  w .j  a  v  a 2  s .  com
 *          the task that failed and must now generate a lame result string
 * @param status
 *          the status code that will go into the lame result string.
 * @return a lame JBI result string
 */
private String makeStatusMessage(String task, String status) {

    /*
     * Cheat sheet: <component-task-result> <component-name>BC1</component-name>
     * <component-task-result-details
     * xmlns="http://java.sun.com/xml/ns/jbi/management- <task-result-details>
     * <task-id>deploy</task-id> <task-result>SUCCESS</task-result>
     * </task-result-details> </component-task-result-details>
     * </component-task-result>
     *
     */

    // First of all, what is the logic why XML ? and if XML, why a String
    // and not a DOM ? But the 64k question is what is wrong with Exceptions?
    Document doc;
    try {
        // Note that we are using our own choice of factory (xerces), not the
        // one that is provided by the system. This is important, otherwise the
        // serialization routine won't work.
        DocumentBuilderFactory dbf = XMLParserUtils.getDocumentBuilderFactory();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.newDocument();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    Element elem = doc.createElementNS(XMLNS_JBI_MGMT, "component-task-result");
    doc.appendChild(elem);
    Element compNameElem = doc.createElementNS(XMLNS_JBI_MGMT, "component-name");
    elem.appendChild(compNameElem);
    Element compTaskRsltDtlsElem = doc.createElementNS(XMLNS_JBI_MGMT, "component-task-result-details");
    elem.appendChild(compTaskRsltDtlsElem);
    Element taskRsltDtlsElem = doc.createElementNS(XMLNS_JBI_MGMT, "task-result-details");
    compTaskRsltDtlsElem.appendChild(taskRsltDtlsElem);

    Element taskId = doc.createElementNS(XMLNS_JBI_MGMT, "task-id");
    taskRsltDtlsElem.appendChild(taskId);

    Element taskResult = doc.createElementNS(XMLNS_JBI_MGMT, "task-result");
    taskRsltDtlsElem.appendChild(taskResult);

    // Why do I have to tell this thing the component name? It /knows/ the
    // component name....
    compNameElem.appendChild(doc.createTextNode(_ode.getContext().getComponentName()));

    // And why on earth do I have to tell my caller the method he just
    // called?
    taskId.appendChild(doc.createTextNode(task));

    taskResult.appendChild(doc.createTextNode(status));
    return DOMUtils.domToString(elem);
}

From source file:org.apache.ode.store.ProcessStoreImpl.java

/**
 * Create a property mapping based on the initial values in the deployment descriptor.
 *
 * @param dd//from w  w w . j  a  v  a2s .c  o  m
 * @return
 */
public static Map<QName, Node> calcInitialProperties(Properties properties, TDeployment.Process dd) {
    HashMap<QName, Node> ret = new HashMap<QName, Node>();

    for (Object key1 : properties.keySet()) {
        String key = (String) key1;
        Document doc = DOMUtils.newDocument();
        doc.appendChild(doc.createElementNS(null, "temporary-simple-type-wrapper"));
        doc.getDocumentElement().appendChild(doc.createTextNode(properties.getProperty(key)));

        ret.put(new QName(key), doc.getDocumentElement());
    }

    for (TDeployment.Process.Property property : dd.getPropertyArray()) {
        Element elmtContent = DOMUtils.getElementContent(property.getDomNode());
        if (elmtContent != null) {
            // We'll need DOM Level 3
            Document doc = DOMUtils.newDocument();
            doc.appendChild(doc.importNode(elmtContent, true));
            ret.put(property.getName(), doc.getDocumentElement());
        } else
            ret.put(property.getName(), property.getDomNode().getFirstChild());

    }
    return ret;
}

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

private static void parse(XMLStreamReader reader, Document doc, Node parent) throws XMLStreamException {
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            // create element
            Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName());
            if (reader.getPrefix() != null && reader.getPrefix() != "") {
                e.setPrefix(reader.getPrefix());
            }// w  ww  .  jav  a2  s .co m
            parent.appendChild(e);

            // copy namespaces
            for (int ns = 0; ns < reader.getNamespaceCount(); ns++) {
                String uri = reader.getNamespaceURI(ns);
                String prefix = reader.getNamespacePrefix(ns);
                declare(e, uri, prefix);
            }

            // copy attributes
            for (int att = 0; att < reader.getAttributeCount(); att++) {
                String name = reader.getAttributeLocalName(att);
                String prefix = reader.getAttributePrefix(att);
                if (prefix != null && prefix.length() > 0) {
                    name = prefix + ":" + name;
                }
                Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name);
                attr.setValue(reader.getAttributeValue(att));
                e.setAttributeNode(attr);
            }
            // sub-nodes
            if (reader.hasNext()) {
                reader.next();
                parse(reader, doc, e);
            }
            if (parent instanceof Document) {
                while (reader.hasNext())
                    reader.next();
                return;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            return;
        case XMLStreamConstants.CHARACTERS:
            if (parent != null) {
                parent.appendChild(doc.createTextNode(reader.getText()));
            }
            break;
        case XMLStreamConstants.COMMENT:
            if (parent != null) {
                parent.appendChild(doc.createComment(reader.getText()));
            }
            break;
        case XMLStreamConstants.CDATA:
            parent.appendChild(doc.createCDATASection(reader.getText()));
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.NAMESPACE:
        case XMLStreamConstants.ATTRIBUTE:
            break;
        default:
            break;
        }

        if (reader.hasNext()) {
            event = reader.next();
        }
    }
}

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

/**
 * Deep clone, but don't fry, the given node in the context of the given document.
 * For all intents and purposes, the clone is the exact same copy of the node,
 * except that it might have a different owner document.
 *
 * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
 * in that it doesn't assume that the given node has a parent or a owner document.
 *
 * @param document//from  w w w  .j a  v  a  2s . co  m
 * @param sourceNode
 * @return a clone of node
 */
public static Node cloneNode(Document document, Node sourceNode) {
    Node clonedNode = null;

    // what is my name?
    QName sourceQName = getNodeQName(sourceNode);
    String nodeName = sourceQName.getLocalPart();
    String namespaceURI = sourceQName.getNamespaceURI();

    // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
    if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
        namespaceURI = null;
    }

    switch (sourceNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        if (namespaceURI == null) {
            clonedNode = document.createAttribute(nodeName);
        } else {
            String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
            // the prefix for the XML namespace can't be looked up, hence this...
            if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
                prefix = "xmlns";
            }
            // if a prefix exists, qualify the name with it
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
            }
            // create the appropriate type of attribute
            if (prefix != null) {
                clonedNode = document.createAttributeNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createAttribute(nodeName);
            }
        }
        break;
    case Node.CDATA_SECTION_NODE:
        clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
        break;
    case Node.COMMENT_NODE:
        clonedNode = document.createComment(((Comment) sourceNode).getData());
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        clonedNode = document.createDocumentFragment();
        break;
    case Node.DOCUMENT_NODE:
        clonedNode = document;
        break;
    case Node.ELEMENT_NODE:
        // create the appropriate type of element
        if (namespaceURI == null) {
            clonedNode = document.createElement(nodeName);
        } else {
            String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns"
                    : ((Element) sourceNode).lookupPrefix(namespaceURI);
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
                clonedNode = document.createElementNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createElement(nodeName);
            }
        }
        // attributes are not treated as child nodes, so copy them explicitly
        NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
            if (attributeClone.getNamespaceURI() == null) {
                ((Element) clonedNode).setAttributeNode(attributeClone);
            } else {
                ((Element) clonedNode).setAttributeNodeNS(attributeClone);
            }
        }
        break;
    case Node.ENTITY_NODE:
        // TODO
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clonedNode = document.createEntityReference(nodeName);
        // TODO
        break;
    case Node.NOTATION_NODE:
        // TODO
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(),
                nodeName);
        break;
    case Node.TEXT_NODE:
        clonedNode = document.createTextNode(((Text) sourceNode).getData());
        break;
    default:
        break;
    }

    // clone children of element and attribute nodes
    NodeList sourceChildren = sourceNode.getChildNodes();
    if (sourceChildren != null) {
        for (int i = 0; i < sourceChildren.getLength(); i++) {
            Node sourceChild = sourceChildren.item(i);
            Node clonedChild = cloneNode(document, sourceChild);
            clonedNode.appendChild(clonedChild);
            // if the child has a textual value, parse it for any embedded prefixes
            if (clonedChild.getNodeType() == Node.TEXT_NODE
                    || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
                parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
            }
        }
    }
    return clonedNode;
}

From source file:org.apache.padaf.xmpbox.SaveMetadataHelper.java

/**
 * Serialize a schema into an Output stream
 * // w  w  w  . j  ava 2s . com
 * @param schema
 *            Schema concerned by the serialization processing
 * @param os
 *            Stream to save serialized schema
 * @throws TransformException
 *             When couldn't parse data to XML/RDF
 */
public static void serialize(XMPSchema schema, OutputStream os) throws TransformException {
    try {
        Document doc = XMLUtil.newDocument();
        Element rdf = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:RDF");
        Node schemContent = schema.getElement().cloneNode(true);
        doc.adoptNode(schemContent);
        rdf.appendChild(schemContent);
        XMLUtil.save(rdf, os, "UTF-8");
    } catch (TransformerException e) {
        throw new TransformException("Failed to parse defined XMP", e);
    } catch (IOException e) {
        throw new TransformException("Failed to create Document to contain Schema representation ", e);
    }

}

From source file:org.apache.rahas.impl.SAML2TokenIssuer.java

/**
 * This method is used to create the subject of an assertion
 * @param config//from w  ww  .j  av a 2 s  .  c om
 * @param doc
 * @param crypto
 * @param creationTime
 * @param expirationTime
 * @param data
 * @return Subject
 * @throws Exception
 */
private Subject createSubjectWithHolderOfKeySC(SAMLTokenIssuerConfig config, Document doc, Crypto crypto,
        DateTime creationTime, DateTime expirationTime, RahasData data) throws Exception {

    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
    SAMLObjectBuilder<Subject> subjectBuilder = (SAMLObjectBuilder<Subject>) builderFactory
            .getBuilder(Subject.DEFAULT_ELEMENT_NAME);
    Subject subject = subjectBuilder.buildObject();
    Element keyInfoElem = null;

    // If it is a Symmetric Key
    if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {

        isSymmetricKeyBasedHoK = true;
        Element encryptedKeyElem;
        X509Certificate serviceCert = null;
        try {
            if (data.getPrincipal() != null) {
                //get subject's name from Rahas data
                String subjectNameID = data.getPrincipal().getName();
                //Create NameID and attach it to the subject
                NameID nameID = new NameIDBuilder().buildObject();
                nameID.setValue(subjectNameID);
                nameID.setFormat(NameIdentifier.EMAIL);
                subject.setNameID(nameID);
            }
            // Get ApliesTo to figure out which service to issue the token
            // for
            serviceCert = config.getServiceCert(crypto, data.getAppliesToAddress());

            // Create the encrypted key
            WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();

            // Use thumbprint id
            encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);

            // SEt the encryption cert
            encrKeyBuilder.setUseThisCert(serviceCert);

            // set keysize
            int keysize = data.getKeysize();
            keysize = (keysize != -1) ? keysize : config.keySize;
            encrKeyBuilder.setKeySize(keysize);

            encrKeyBuilder
                    .setEphemeralKey(TokenIssuerUtil.getSharedSecret(data, config.keyComputation, keysize));

            // Set key encryption algo
            encrKeyBuilder.setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);

            // Build
            encrKeyBuilder.prepare(doc, crypto);

            // Extract the base64 encoded secret value
            byte[] tempKey = new byte[keysize / 8];
            System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey, 0, keysize / 8);

            data.setEphmeralKey(tempKey);

            // Extract the Encryptedkey DOM element
            encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
        } catch (WSSecurityException e) {
            throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal",
                    new String[] { serviceCert.getSubjectDN().getName() }, e);
        }

        keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
        ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
        ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX);

        keyInfoElem.appendChild(encryptedKeyElem);

    }

    // If it is a public Key
    else if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {
        try {
            String subjectNameId = data.getPrincipal().getName();

            //Create NameID and attach it to the subject
            NameIDBuilder nb = new NameIDBuilder();
            NameID nameID = nb.buildObject();
            nameID.setValue(subjectNameId);
            nameID.setFormat(NameIdentifier.EMAIL);
            subject.setNameID(nameID);

            // Create the ds:KeyValue element with the ds:X509Data
            X509Certificate clientCert = data.getClientCert();

            if (clientCert == null) {
                X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName());
                clientCert = certs[0];
            }

            byte[] clientCertBytes = clientCert.getEncoded();

            String base64Cert = Base64.encode(clientCertBytes);

            Text base64CertText = doc.createTextNode(base64Cert);

            //-----------------------------------------

            Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Certificate");
            x509CertElem.appendChild(base64CertText);
            Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Data");
            x509DataElem.appendChild(x509CertElem);

            if (x509DataElem != null) {
                keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
                ((OMElement) x509DataElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
                keyInfoElem.appendChild(x509DataElem);
            }

        } catch (Exception e) {
            throw new TrustException("samlAssertionCreationError", e);
        }
    }

    // Unmarshall the keyInfo DOM element into an XMLObject
    String keyInfoElementString = keyInfoElem.toString();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes()));
    Element element = document.getDocumentElement();

    // Get appropriate unmarshaller
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

    // Unmarshall using the document root element, an keyInfo element in this case
    XMLObject keyInfoElement = null;
    try {
        keyInfoElement = unmarshaller.unmarshall(element);
    } catch (UnmarshallingException e) {
        throw new TrustException("Error unmarshalling KeyInfo Element", e);
    }

    //Build the Subject Confirmation
    SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) builderFactory
            .getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();

    //Set the subject Confirmation method
    subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key");

    SAMLObjectBuilder<KeyInfoConfirmationDataType> keyInfoSubjectConfirmationDataBuilder = (SAMLObjectBuilder<KeyInfoConfirmationDataType>) builderFactory
            .getBuilder(KeyInfoConfirmationDataType.TYPE_NAME);

    //Build the subject confirmation data element
    KeyInfoConfirmationDataType scData = keyInfoSubjectConfirmationDataBuilder
            .buildObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME, KeyInfoConfirmationDataType.TYPE_NAME);

    //Set the keyInfo element
    scData.getKeyInfos().add(keyInfoElement);

    // Set the validity period
    scData.setNotBefore(creationTime);
    scData.setNotOnOrAfter(expirationTime);

    //Set the subject confirmation data
    subjectConfirmation.setSubjectConfirmationData(scData);

    //set the subject confirmation
    subject.getSubjectConfirmations().add(subjectConfirmation);

    log.debug("SAML2.0 subject is constructed successfully.");
    return subject;
}

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

protected SAMLAssertion createHoKAssertion(SAMLTokenIssuerConfig config, Document doc, Crypto crypto,
        Date creationTime, Date expirationTime, RahasData data) throws TrustException {

    String keyType = data.getKeyType();
    if (StringUtils.isBlank(keyType)) {
        keyType = data.getRstElement().getNamespace().getNamespaceURI() + RahasConstants.KEY_TYPE_SYMM_KEY;
    }/*w  w  w .  j  a  va2s .  c  om*/

    if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
        Element encryptedKeyElem;
        SAMLNameIdentifier nameId = null;
        X509Certificate serviceCert = null;
        try {
            if (data.getPrincipal() != null) {
                String subjectNameId = data.getPrincipal().getName();
                nameId = new SAMLNameIdentifier(subjectNameId, null, SAMLNameIdentifier.FORMAT_EMAIL);
            }

            // Get ApliesTo to figure out which service to issue the token
            // for
            serviceCert = getServiceCert(config, crypto, data.getAppliesToAddress());

            // Create the encrypted key
            WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();

            // Use thumbprint id
            encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);

            // SEt the encryption cert
            encrKeyBuilder.setUseThisCert(serviceCert);

            // set keysize
            int keysize = data.getKeysize();
            keysize = (keysize != -1) ? keysize : config.keySize;
            encrKeyBuilder.setKeySize(keysize);

            encrKeyBuilder
                    .setEphemeralKey(TokenIssuerUtil.getSharedSecret(data, config.keyComputation, keysize));

            // Set key encryption algo
            encrKeyBuilder.setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);

            // Build
            encrKeyBuilder.prepare(doc, crypto);

            // Extract the base64 encoded secret value
            byte[] tempKey = new byte[keysize / 8];
            System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey, 0, keysize / 8);

            data.setEphmeralKey(tempKey);

            // Extract the Encryptedkey DOM element
            encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
        } catch (Exception e) {
            throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal",
                    new String[] { serviceCert.getSubjectDN().getName() }, e);
        }
        return this.createAttributeAssertion(doc, data, encryptedKeyElem, nameId, config, crypto, creationTime,
                expirationTime);
    } else {
        try {
            String subjectNameId = data.getPrincipal().getName();

            SAMLNameIdentifier nameId = new SAMLNameIdentifier(subjectNameId, null,
                    SAMLNameIdentifier.FORMAT_EMAIL);

            // Create the ds:KeyValue element with the ds:X509Data
            X509Certificate clientCert = data.getClientCert();

            if (clientCert == null) {
                X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName());
                clientCert = certs[0];
            }

            byte[] clientCertBytes = clientCert.getEncoded();

            String base64Cert = Base64.encode(clientCertBytes);

            Text base64CertText = doc.createTextNode(base64Cert);
            Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS, "X509Certificate");
            x509CertElem.appendChild(base64CertText);
            Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "X509Data");
            x509DataElem.appendChild(x509CertElem);

            return this.createAuthAssertion(doc, SAMLSubject.CONF_HOLDER_KEY, nameId, x509DataElem, config,
                    crypto, creationTime, expirationTime, data);
        } catch (Exception e) {
            throw new TrustException("samlAssertionCreationError", e);
        }
    }
}