Example usage for org.w3c.dom Element setTextContent

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

Introduction

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

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:eu.impact_project.iif.tw.gen.DeploymentCreator.java

/**
 * Insert data types//  w w  w . java2s.c o m
 * @throws GeneratorException 
 */
public void createPom() throws GeneratorException {
    File wsdlTemplate = new File(this.pomAbsPath);
    if (!wsdlTemplate.canRead()) {
        throw new GeneratorException("Unable to read pom.xml template file: " + this.pomAbsPath);
    }
    try {

        DocumentBuilderFactory docBuildFact = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuildFact.newDocumentBuilder();
        doc = docBuilder.parse(this.pomAbsPath);
        NodeList profilesNodes = doc.getElementsByTagName("profiles");
        Node firstProfilesNode = profilesNodes.item(0);
        List<Deployref> dks = service.getDeployto().getDeployref();

        NodeList executionsNode = doc.getElementsByTagName("executions");
        Node thirdExecutionsNode = executionsNode.item(2);

        for (Deployref dk : dks) {
            boolean isDefaultDeployment = dk.isDefault();
            Deployment d = (Deployment) dk.getRef();

            String host = d.getHost();
            String id = d.getId();

            //<profile>
            //    <id>deployment1</id>
            //    <properties>
            //        <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url>
            //        <tomcat.user>tomcat</tomcat.user>
            //        <tomcat.password>TxF781!P</tomcat.password>
            //        <war.suffix>deployment1</war.suffix>
            //    </properties>
            //</profile>
            //<profile>
            //    <id>deployment2</id>
            //    <properties>
            //        <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url>
            //        <tomcat.user>tomcat</tomcat.user>
            //        <tomcat.password>TxF781!P</tomcat.password>
            //        <war.suffix>deployment2</war.suffix>
            //    </properties>
            //</profile>
            Element profileElm = doc.createElement("profile");

            if (isDefaultDeployment) {
                Element activationElm = doc.createElement("activation");
                Element activeByDefaultElm = doc.createElement("activeByDefault");
                activeByDefaultElm.setTextContent("true");
                activationElm.appendChild(activeByDefaultElm);
                profileElm.appendChild(activationElm);
            }

            firstProfilesNode.appendChild(profileElm);
            Element idElm = doc.createElement("id");
            idElm.setTextContent(d.getId());
            profileElm.appendChild(idElm);
            Element propertiesElm = doc.createElement("properties");
            profileElm.appendChild(propertiesElm);

            List<Port> ports = d.getPorts().getPort();
            String port = "8080";
            String type = "http";
            for (Port p : ports) {
                if (p.getType().equals("http")) {
                    port = String.valueOf(p.getValue());
                    type = p.getType();
                }
            }

            Element tomcatManagerUrlElm = doc.createElement("tomcat.manager.url");
            String managerPath = d.getManager().getPath();
            managerPath = (managerPath != null && !managerPath.isEmpty()) ? managerPath : "manager";
            tomcatManagerUrlElm.setTextContent(type + "://" + d.getHost() + ":" + port + "/" + managerPath);

            propertiesElm.appendChild(tomcatManagerUrlElm);
            Element tomcatUserPropElm = doc.createElement("tomcat.user");
            Manager manager = d.getManager();
            tomcatUserPropElm.setTextContent(manager.getUser());
            propertiesElm.appendChild(tomcatUserPropElm);
            Element tomcatPasswordPropElm = doc.createElement("tomcat.password");
            tomcatPasswordPropElm.setTextContent(manager.getPassword());
            propertiesElm.appendChild(tomcatPasswordPropElm);
            Element warSuffixElm = doc.createElement("war.suffix");
            warSuffixElm.setTextContent(d.getId());
            propertiesElm.appendChild(warSuffixElm);

            //<execution>
            //    <id>package-deployment1</id>
            //    <phase>package</phase>
            //    <configuration>
            //        <classifier>deployment1</classifier>
            //        <webappDirectory>${project.build.directory}/${project.build.finalName}_deployment1</webappDirectory>
            //        <webResources>
            //            <resource>
            //                <directory>src/env/deployment1</directory>
            //            </resource>
            //        </webResources>
            //    </configuration>
            //    <goals>
            //        <goal>war</goal>
            //    </goals>
            //</execution>

            Element executionElm = doc.createElement("execution");
            Element id2Elm = doc.createElement("id");
            id2Elm.setTextContent("package-" + d.getId());
            executionElm.appendChild(id2Elm);
            Element phaseElm = doc.createElement("phase");
            phaseElm.setTextContent("package");
            executionElm.appendChild(phaseElm);
            Element configurationElm = doc.createElement("configuration");
            executionElm.appendChild(configurationElm);
            Element classifierElm = doc.createElement("classifier");
            classifierElm.setTextContent(d.getId());
            configurationElm.appendChild(classifierElm);
            Element webappDirectoryElm = doc.createElement("webappDirectory");
            webappDirectoryElm
                    .setTextContent("${project.build.directory}/${project.build.finalName}_" + d.getId());
            configurationElm.appendChild(webappDirectoryElm);
            Element webResourcesElm = doc.createElement("webResources");
            Element resourceElm = doc.createElement("resource");
            Element directoryElm = doc.createElement("directory");
            directoryElm.setTextContent("src/env/" + d.getId());
            resourceElm.appendChild(directoryElm);
            webResourcesElm.appendChild(resourceElm);
            configurationElm.appendChild(webResourcesElm);
            Element goalsElm = doc.createElement("goals");
            executionElm.appendChild(goalsElm);
            Element goalElm = doc.createElement("goal");
            goalElm.setTextContent("war");
            goalsElm.appendChild(goalElm);
            thirdExecutionsNode.appendChild(executionElm);

            if (isDefaultDeployment) {
                NodeList directories = doc.getElementsByTagName("directory");
                Node directoryNode = directories.item(0);
                directoryNode.setTextContent("src/env/" + d.getId());
            }

            // Create different environment dependent configuration files.
            // Deployment environment dependent files will be stored in
            // src/env and will then be activated by choosing the corresponding
            // profile during the corresponding maven phase.
            // E.g. mvn tomcat:redeploy -P deployment1
            // will replace the deployment dependent files by the ones
            // available under src/env/deployment1.
            String generatedDir = st.getGenerateDir();
            String projMidfix = st.getProjectMidfix();
            String projDir = st.getProjectDirectory();
            String servDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId(), "WEB-INF/services",
                    projMidfix, "META-INF");
            FileUtils.forceMkdir(new File(servDir));

            String sxmlFile = FileUtil.makePath(generatedDir, projDir, "src/main/webapp/WEB-INF/services",
                    st.getProjectMidfix(), "META-INF") + "services.xml";

            GenericCode deplDepServXmlCode = new GenericCode(sxmlFile);

            //<parameter name="cliCommand1">${clicmd}</parameter>
            //<parameter name="processingUnit">${tomcat_public_procunitid}</parameter>
            //<parameter name="publicHttpAccessDir">${tomcat_public_http_access_dir}</parameter>
            //<parameter name="publicHttpAccessUrl">${tomcat_public_http_access_url}</parameter>
            //<parameter name="serviceUrlFilter">${service_url_filter}</parameter>
            List<Operation> operations = service.getOperations().getOperation();
            for (Operation operation : operations) {
                String command = operation.getCommand();
                String toolsbasedir = d.getToolsbasedir();
                if (toolsbasedir != null && !toolsbasedir.equals("")) {
                    command = toolsbasedir + command;
                }
                deplDepServXmlCode.put("cli_cmd_" + String.valueOf(operation.getOid()), command);
            }

            deplDepServXmlCode.put("tomcat_public_procunitid", d.getIdentifier());
            Dataexchange de = d.getDataexchange();

            String accessDir = FileUtil.makePath(de.getAccessdir());
            String accessUrl = de.getAccessurl();

            deplDepServXmlCode.put("tomcat_public_http_access_dir", accessDir);
            deplDepServXmlCode.put("tomcat_public_http_access_url", accessUrl);
            // TODO: filter
            //deplDepServXmlCode.put("service_url_filter", );
            deplDepServXmlCode.evaluate();

            deplDepServXmlCode.create(servDir + "services.xml");
            logger.debug("Writing: " + servDir + "services.xml");
            if (isDefaultDeployment) {
                defaultDeplServicesFile = servDir + "services.xml";
                defaultServicesFile = sxmlFile;
            }

            // source
            String htmlIndexSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp")
                    + "index.html";
            // substitution
            GenericCode htmlSourceIndexCode = new GenericCode(htmlIndexSourcePath);
            htmlSourceIndexCode.put("service_description", service.getDescription());
            htmlSourceIndexCode.put("tomcat_public_host", d.getHost());
            htmlSourceIndexCode.put("tomcat_public_http_port", port);
            // target
            String htmlIndexDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId());
            FileUtils.forceMkdir(new File(htmlIndexDir));
            String htmlIndexTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId())
                    + "index.html";
            htmlSourceIndexCode.create(htmlIndexTargetPath);
            if (isDefaultDeployment) {
                this.defaultDeplHtmlFile = htmlIndexTargetPath;
                this.defaultHtmlFile = htmlIndexSourcePath;
            }

            // source
            String wsdlSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp")
                    + st.getProjectMidfix() + ".wsdl";
            // substitution
            GenericCode wsdlSourceCode = new GenericCode(wsdlSourcePath);
            wsdlSourceCode.put("tomcat_public_host", d.getHost());
            wsdlSourceCode.put("tomcat_public_http_port", port);
            // target
            String wsdlDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId());
            FileUtils.forceMkdir(new File(wsdlDir));
            String wsdlTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId())
                    + st.getProjectMidfix() + ".wsdl";
            wsdlSourceCode.create(wsdlTargetPath);
            if (isDefaultDeployment) {
                this.defaultDeplWsdlFile = wsdlTargetPath;
                this.defaultWsdlFile = wsdlSourcePath;
            }
        }
        if (defaultDeplServicesFile != null && !defaultDeplServicesFile.isEmpty()) {
            FileUtils.copyFile(new File(defaultDeplServicesFile), new File(defaultServicesFile));
            FileUtils.copyFile(new File(this.defaultDeplHtmlFile), new File(this.defaultHtmlFile));
            FileUtils.copyFile(new File(this.defaultDeplWsdlFile), new File(this.defaultWsdlFile));
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(doc);
        FileOutputStream fos = new FileOutputStream(this.pomAbsPath);
        StreamResult result = new StreamResult(fos);
        transformer.transform(source, result);
        fos.close();
    } catch (Exception ex) {
        logger.error("An exception occurred: " + ex.getMessage());
    }
}

From source file:com.photon.phresco.service.tools.TechnologyDataGenerator.java

/**
 * Create pom.xml file for each module/*from w  w w .  j  av a2 s. co  m*/
 * @param module
 * @param ext
 * @param groupId2
 * @return
 * @throws PhrescoException
 */
private File createPomFile(String name, String groupId, String artifactId, String version, String ext)
        throws PhrescoException {
    System.out.println("Creating Pom File For " + name);
    File file = new File(outputRootDir, "pom.xml");
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

        org.w3c.dom.Document newDoc = domBuilder.newDocument();
        Element rootElement = newDoc.createElement("project");
        newDoc.appendChild(rootElement);

        Element modelVersion = newDoc.createElement("modelVersion");
        modelVersion.setTextContent("4.0.0");
        rootElement.appendChild(modelVersion);

        Element groupIdEle = newDoc.createElement("groupId");
        groupIdEle.setTextContent(groupId);
        rootElement.appendChild(groupIdEle);

        Element artifactIdEle = newDoc.createElement("artifactId");
        artifactIdEle.setTextContent(artifactId);
        rootElement.appendChild(artifactIdEle);

        Element versionEle = newDoc.createElement("version");
        versionEle.setTextContent(version);
        rootElement.appendChild(versionEle);

        Element packaging = newDoc.createElement("packaging");
        packaging.setTextContent(ext);
        rootElement.appendChild(packaging);

        Element description = newDoc.createElement("description");
        description.setTextContent("created by phresco");
        rootElement.appendChild(description);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(newDoc);
        trans.transform(source, result);
        String xmlString = sw.toString();
        FileWriter writer = new FileWriter(file);
        writer.write(xmlString);
        writer.close();

    } catch (Exception e) {
        throw new PhrescoException();
    }
    return file;
}

From source file:eu.optimis.mi.aggregator.util.XmlUtil.java

public String getObjXml(String xml) {
    try {//from  w ww  .j a v a  2 s.com
        // Create a builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        NodeList timestampList = doc.getElementsByTagName("metric_timestamp");
        for (int i = 0; i < timestampList.getLength(); i++) {
            Element ts = (Element) timestampList.item(i);
            String tsLangType = ts.getTextContent();
            try {
                long millis = 0;
                millis = Long.parseLong(tsLangType);
                Date udate = new Date(millis * 1000);
                String timestamp = DateFormatUtils.ISO_DATETIME_FORMAT.format(udate);
                ts.setTextContent(timestamp);
            } catch (NumberFormatException e) {
            }
        }
        String rs = xmlToString(doc);
        return rs;

    } catch (SAXException e) {
        return null;
    } catch (ParserConfigurationException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????.//w  w  w. j av a  2s  .c  om
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

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

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return DcCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java

public void postSign(byte[] signatureValue, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    /*//from w ww. j  ava 2 s. c om
     * Retrieve the intermediate XML signature document from the temporary
     * data storage.
     */
    TemporaryDataStorage temporaryDataStorage = getTemporaryDataStorage();
    InputStream documentInputStream = temporaryDataStorage.getTempInputStream();
    String signatureId = (String) temporaryDataStorage.getAttribute(SIGNATURE_ID_ATTRIBUTE);
    LOG.debug("signature Id: " + signatureId);

    /*
     * Load the signature DOM document.
     */
    Document document;
    try {
        document = loadDocument(documentInputStream);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }

    /*
     * Locate the correct ds:Signature node.
     */
    Element nsElement = document.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    Element signatureElement;
    try {
        signatureElement = (Element) XPathAPI.selectSingleNode(document,
                "//ds:Signature[@Id='" + signatureId + "']", nsElement);
    } catch (TransformerException e) {
        throw new RuntimeException("XPATH error: " + e.getMessage(), e);
    }
    if (null == signatureElement) {
        throw new RuntimeException("ds:Signature not found for @Id: " + signatureId);
    }

    /*
     * Insert signature value into the ds:SignatureValue element
     */
    NodeList signatureValueNodeList = signatureElement
            .getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, "SignatureValue");
    Element signatureValueElement = (Element) signatureValueNodeList.item(0);
    signatureValueElement.setTextContent(Base64.encode(signatureValue));

    //LOG.debug("signatureValue: "+Base64.encode(signatureValue));
    /*
     * Allow signature facets to inject their own stuff.
     */
    for (SignatureFacet signatureFacet : this.signatureFacets) {
        signatureFacet.postSign(signatureElement, signingCertificateChain);
    }

    OutputStream signedDocumentOutputStream = getSignedDocumentOutputStream();
    if (null == signedDocumentOutputStream) {
        throw new IllegalArgumentException("signed document output stream is null");
    }
    try {
        writeDocument(document, signedDocumentOutputStream);
    } catch (Exception e) {
        LOG.debug("error writing the signed XML document: " + e.getMessage(), e);
        throw new RuntimeException("error writing the signed XML document: " + e.getMessage(), e);
    }
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????./*  ww  w . ja v  a  2  s . c  o  m*/
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

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

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return PersoniumCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:com.github.wesjd.overcastmappacker.xml.DocumentHandler.java

public void set(Class<? extends ParentXMLModule> parentClass, Class<? extends XMLModule> moduleClass,
        String moduleValue, ContinuingMap<String, String> attributeMapping) {
    final Map<String, String> rawAttributeMapping = attributeMapping.getRaw();
    final XMLModule module = XMLModule.of(moduleClass);

    ParentXMLModule parentModule = XMLConstants.MAIN_BODY_MODULE;
    if (parentClass != null)
        parentModule = (ParentXMLModule) XMLModule.of(parentClass);
    Validate.isTrue(//  ww w.jav  a 2 s .  c o m
            parentModule.getChildXMLModules() == null
                    || parentModule.getChildXMLModules().contains(module.getClass()),
            "Parent module must accept child.");

    Element moduleElement = (Element) document.getElementsByTagName(module.getTag()).item(0);
    if (moduleElement == null) {
        moduleElement = document.createElement(module.getTag());

        Node parentNode = document.getElementsByTagName(parentModule.getTag()).item(0);
        if (parentNode == null) {
            set(null, parentModule.getClass());
            parentNode = document.getElementsByTagName(parentModule.getTag()).item(0);
        }
        parentNode.appendChild(moduleElement);
    }
    moduleElement.setTextContent(moduleValue);

    if (module.getXMLAttributes() != null) {
        final Element finalModuleElement = moduleElement;
        module.getXMLAttributes().forEach(xmlAttribute -> {
            final String attributeName = xmlAttribute.getName();

            String value = rawAttributeMapping.containsKey(attributeName)
                    ? rawAttributeMapping.get(attributeName)
                    : xmlAttribute.getDefaultValue();
            if ((xmlAttribute.getValidValues() == null || !xmlAttribute.getValidValues().contains(value))
                    && xmlAttribute.isRequired())
                value = xmlAttribute.getDefaultValue();

            finalModuleElement.setAttribute(attributeName, value);
        });
    }
}

From source file:fr.adfab.magebeans.processes.CreateModuleProcess.java

protected void _createNode(String xpath, String value) {
    String[] nodes = xpath.split("/");
    Element parent = this.globalElement;
    for (String node : nodes) {
        NodeList nodeList = parent.getElementsByTagName(node);
        if (nodeList == null || nodeList.getLength() == 0) {
            Element newElement = this.dom.createElement(node);
            parent.appendChild(newElement);
            parent = newElement;//from   ww  w .  java  2 s  .c o m
        } else {
            parent = (Element) nodeList.item(0);
        }
    }
    parent.setTextContent(value);
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

private Node makeEntityResolutionConfigurationNode(String limit) throws Exception {
    try {/*w w  w  .ja va  2 s  .c o m*/
        if (Integer.parseInt(limit) == Integer.MAX_VALUE) {
            return null;
        }
    } catch (NumberFormatException nfe) {
        return null;
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.newDocument();
    Element ret = d.createElementNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE,
            "EntityResolutionConfiguration");
    d.appendChild(ret);
    Element e = d.createElementNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "RecordLimit");
    ret.appendChild(e);
    e.setTextContent(limit);
    return ret;
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

/**
 * Sets the given value element. The <code>type</code> is set to the given runtime type.
 * String form of the given object is set as the text content.
 *
 * @param element     the XML element to be set
 * @param obj         value of the element. Never null.
 * @param runtimeType attribute type//from  w  ww . ja  va2 s  . com
 */
protected void encodeBasic(Element element, Object obj, Class<?> runtimeType) {
    element.setTextContent(obj == null ? NULL_VALUE : obj.toString());
}