Example usage for org.w3c.dom Node setTextContent

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

Introduction

In this page you can find the example usage for org.w3c.dom Node 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:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java

private void updateEncrySrvConfig(String newPwd, String newSalt) {
    try {/*ww w .j a va 2s .c o m*/
        final String encryptKeyTag = "encrypt-key";
        final String encryptSaltTag = "encrypt-salt";
        LOG.debug("Update encryption service config file");
        final File configFile = new File(DEFAULT_CONFIG_FILE_PATH);
        if (configFile.exists()) {
            final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            final Document doc = docBuilder.parse(configFile);
            final Node key = doc.getElementsByTagName(encryptKeyTag).item(0);
            key.setTextContent(newPwd);
            final Node salt = doc.getElementsByTagName(encryptSaltTag).item(0);
            salt.setTextContent(newSalt);
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            final DOMSource source = new DOMSource(doc);
            final StreamResult result = new StreamResult(new File(DEFAULT_CONFIG_FILE_PATH));
            transformer.transform(source, result);
        } else {
            LOG.warn("The encryption service config file does not exist {}", DEFAULT_CONFIG_FILE_PATH);
        }
    } catch (ParserConfigurationException | TransformerException | SAXException | IOException e) {
        LOG.error("Error while updating the encryption service config file", e);
    }
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java

/**
 * Constructs a CDA Consent for the given user.
 * //from ww  w .j  av  a  2s.  c  o m
 * @param user
 * @param policySet
 *            - null if either the participation should end or if a new
 *            PolicySet should be created.
 * @param author
 * @param participation
 *            - true if the user wants to participate, else false
 * @param out
 *            - The OutputStream on which the generated PDF presentation
 *            will be written
 * @return - The generated CDA file.
 * 
 */
public Document constructCDA(User user, Document policySet, User author, boolean participation,
        OutputStream out) {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document domCDA = null;
    Document domAssignedAuthor = null;
    Document domScanningDevice = null;
    Document domDataEnterer = null;
    Document domCustodian = null;
    Document domLegalAuthenticator = null;
    String cdaAsString = "";

    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();

        domCDA = db.parse(urlCdaSkeleton);
        domAssignedAuthor = db.parse(urlAssignedAuthor);
        domScanningDevice = db.parse(urlScanningDevice);
        domDataEnterer = db.parse(urlDataEnterer);
        domCustodian = db.parse(urlCustodian);
        domLegalAuthenticator = db.parse(urlLegalAuthenticator);

    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }

    Date d = new Date();

    String uniqueID = RandomStringUtils.randomNumeric(64);

    domCDA.getElementsByTagName("id").item(0).getAttributes().item(0).setNodeValue(uniqueID);
    domCDA.getElementsByTagName("id").item(0).getAttributes().item(1)
            .setNodeValue("1.2.276.0.76.3.1.78.1.0.10.40");

    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssZ");

    domCDA.getElementsByTagName("effectiveTime").item(0).getAttributes().item(0).setTextContent(sd.format(d));

    Node title = domCDA.getElementsByTagName("title").item(0);

    if (participation) {
        title.setTextContent("Dies ist die Einwilligungserklrung fr die Teilnahme an ISIS von "
                + user.getForename() + " " + user.getName());
    } else {
        title.setTextContent("Dieses Dokument erklrt den Verzicht von " + user.getForename() + " "
                + user.getName() + " auf die Teilnahme an ISIS.");
    }

    Node pR = domCDA.getElementsByTagName("patientRole").item(0);

    NodeList prChildren = pR.getChildNodes();

    Node id = prChildren.item(1);

    // extension
    id.getAttributes().item(0).setNodeValue(user.getID()); // PID
    // root
    id.getAttributes().item(1).setNodeValue("1.2.276.0.76.3.1.78.1.0.10.20"); // Assigning
    // Authority

    NodeList addr = prChildren.item(3).getChildNodes();

    addr.item(1).setTextContent(user.getStreet());
    addr.item(3).setTextContent(user.getCity());
    addr.item(5).setTextContent("");//Hier knnte das Bundesland
    // stehen!

    addr.item(7).setTextContent(String.valueOf(user.getZipcode()));
    addr.item(9).setTextContent("Deutschland");// Es sollte nicht
    // standardmig Deutschland
    // gesetzt werden!

    NodeList pat = prChildren.item(5).getChildNodes();

    NodeList name = pat.item(1).getChildNodes();

    if (user.getGender().equalsIgnoreCase("male")) {
        name.item(1).setTextContent("Herr");
        pat.item(3).getAttributes().item(0).setTextContent("M");
    } else {
        name.item(1).setTextContent("Frau");
        pat.item(3).getAttributes().item(0).setTextContent("F");
    }
    name.item(3).setTextContent(user.getForename());
    name.item(5).setTextContent(user.getName());

    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

    pat.item(5).getAttributes().item(0).setTextContent(formatter.format(user.getBirthdate()));

    if (policySet == null) {
        policySet = getSkeletonPolicySet(participation, user);

    }
    Document doc = db.newDocument();

    Element root = doc.createElement("component");
    doc.appendChild(root);

    Node copy = doc.importNode(policySet.getDocumentElement(), true);
    root.appendChild(copy);

    NodeList list = domCDA.getElementsByTagName("structuredBody");

    Node f = domCDA.importNode(doc.getDocumentElement(), true);

    list.item(0).appendChild(f);

    Node docuOfNode = domCDA.getElementsByTagName("documentationOf").item(0);

    if (author == user) {

        domAssignedAuthor.getElementsByTagName("time").item(0).getAttributes().item(0)
                .setNodeValue(sd.format(d));

        domAssignedAuthor.getElementsByTagName("id").item(0).getAttributes().item(0)
                .setNodeValue(author.getID()); // ID
        domAssignedAuthor.getElementsByTagName("id").item(0).getAttributes().item(1)
                .setNodeValue("1.2.276.0.76.3.1.78.1.0.10.20");// MPI-assigning
        // authority

        if (user.getGender().equalsIgnoreCase("male")) {
            domAssignedAuthor.getElementsByTagName("prefix").item(0).setTextContent("Herr");
        } else {
            name.item(1).setTextContent("Frau");
            domAssignedAuthor.getElementsByTagName("prefix").item(0).setTextContent("Frau");
        }

        // suffix Wert setzen
        // domAssignedAuthor.getElementsByTagName("suffix").item(0).getAttributes().item(0).setNodeValue("");

        domAssignedAuthor.getElementsByTagName("given").item(0).setTextContent(author.getForename());
        domAssignedAuthor.getElementsByTagName("family").item(0).setTextContent(author.getName());

        // TODO Werte setzen assignedPerson oder Werte loeschen
    } else if (author != user && author != null) {
        // Zukunft: Erzeugung durch Dritte
    } else {
        // Std values from AssignedAuthor.xml
    }

    Node copyAssignedAuthorNode = domCDA.importNode(domAssignedAuthor.getDocumentElement(), true);
    Node copyScanningDeviceNode = domCDA.importNode(domScanningDevice.getDocumentElement(), true);
    Node copyDataEntererNode = domCDA.importNode(domDataEnterer.getDocumentElement(), true);
    Node copyCustodianNode = domCDA.importNode(domCustodian.getDocumentElement(), true);
    Node copyLegalAuthenticator = domCDA.importNode(domLegalAuthenticator.getDocumentElement(), true);

    sd.applyPattern("yyyyMMdd");

    domCDA.getElementsByTagName("low").item(0).getAttributes().item(0).setNodeValue(sd.format(d));

    Date d2 = new Date((long) (d.getTime() + 30 * 3.1556926 * Math.pow(10, 10)));

    domCDA.getElementsByTagName("high").item(0).getAttributes().item(0).setNodeValue(sd.format(d2));

    copyAssignedAuthorNode.getChildNodes().item(3).getAttributes().item(0).setNodeValue(sd.format(d));

    Node clinicalDocumentNode = domCDA.getElementsByTagName("ClinicalDocument").item(0);

    clinicalDocumentNode.insertBefore(copyAssignedAuthorNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyScanningDeviceNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyDataEntererNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyCustodianNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyLegalAuthenticator, docuOfNode);

    Document noNSCDA = (Document) domCDA.cloneNode(true);

    NodeList l = noNSCDA.getElementsByTagName("ClinicalDocument");

    NamedNodeMap attributes = l.item(0).getAttributes();
    attributes.removeNamedItem("xmlns");
    attributes.removeNamedItem("xmlns:voc");
    attributes.removeNamedItem("xmlns:xsi");
    attributes.removeNamedItem("xsi:schemaLocation");

    l = noNSCDA.getElementsByTagName("PolicySet");
    attributes = l.item(0).getAttributes();
    attributes.removeNamedItem("xmlns");
    attributes.removeNamedItem("PolicyCombiningAlgId");
    attributes.removeNamedItem("xmlns:xsi");
    attributes.removeNamedItem("xsi:schemaLocation");
    attributes.removeNamedItem("PolicySetId");

    formatter = new SimpleDateFormat("dd.MM.yyyy");

    noNSCDA.getElementsByTagName("birthTime").item(0).getAttributes().item(0)
            .setTextContent(formatter.format(user.getBirthdate()));

    cdaAsString = getStringFromDocument(noNSCDA);
    Document nonXMLBody = constructPDF(cdaAsString, out);

    Node copyNode = domCDA.importNode(nonXMLBody.getDocumentElement(), true);

    Node component = domCDA.getElementsByTagName("component").item(0);

    Node structBody = component.getChildNodes().item(1);

    component.insertBefore(copyNode, structBody);

    NamedNodeMap nlm = domCDA.getDocumentElement().getElementsByTagName("PolicySet").item(0).getAttributes();
    // nlm.removeNamedItem("xmlns:xsi");
    // nlm.removeNamedItem("xsi:schemaLocation");

    return domCDA;
}

From source file:org.openengsb.openengsbplugin.base.ConfiguredMojo.java

private void insertConfigProfileIntoOrigPom(Document originalPom, Document mojoConfiguration,
        String profileName) throws XPathExpressionException {
    Node profileNode = mojoConfiguration.getFirstChild();

    Node idNode = mojoConfiguration.createElementNS(POM_NS_URI, "id");
    idNode.setTextContent(profileName);
    profileNode.insertBefore(idNode, profileNode.getFirstChild());

    Node importedProfileNode = originalPom.importNode(profileNode, true);

    Tools.insertDomNode(originalPom, importedProfileNode, POM_PROFILE_XPATH, NS_CONTEXT);
}

From source file:org.openengsb.openengsbplugin.base.LicenseMojo.java

public static void insertGoalAndSetHeaderPath(Document configuredPom, String profileXpath, String goalToInsert,
        String headerPathToInsert) throws XPathExpressionException {
    Node node = configuredPom.createElementNS(POM_NS_URI, "goal");
    node.setTextContent(goalToInsert);

    String licensePluginXPath = profileXpath + "/pom:build/pom:plugins/pom:plugin"
            + "[pom:groupId='com.mycila.maven-license-plugin' and pom:artifactId='maven-license-plugin']";

    Tools.insertDomNode(configuredPom, node, licensePluginXPath + "/pom:executions/pom:execution/pom:goals",
            NS_CONTEXT);/*from w w w  .  ja  va 2  s  .com*/

    LOG.trace(String.format("headerPath: \"%s\"", headerPathToInsert));

    node = configuredPom.createElementNS(POM_NS_URI, "header");
    node.setTextContent(headerPathToInsert);

    Tools.insertDomNode(configuredPom, node, licensePluginXPath + "/pom:configuration", NS_CONTEXT);
}

From source file:org.openengsb.openengsbplugin.base.LicenseMojo.java

public static void addExcludes(Document configuredPom, String profileXpath, String excludesFilePath)
        throws IOException, XPathExpressionException {
    if (excludesFilePath == null) {
        return;/*  w w w  .j  a  va 2  s .  c o m*/
    }
    File excludesFile = new File(excludesFilePath);
    if (!excludesFile.exists()) {
        return;
    }

    String insertPath = profileXpath + "/pom:build/pom:plugins/pom:plugin"
            + "[pom:groupId='com.mycila.maven-license-plugin' and pom:artifactId='maven-license-plugin']"
            + "/pom:configuration/pom:excludes";

    List<String> lines = FileUtils.readLines(excludesFile);
    for (String line : lines) {
        if (line == null || line.trim().equals("")) {
            continue;
        }
        LOG.trace(String.format("adding exclude: %s", line));
        Node node = configuredPom.createElementNS(POM_NS_URI, "exclude");
        node.setTextContent(line.trim());
        Tools.insertDomNode(configuredPom, node, insertPath, NS_CONTEXT);
    }
}

From source file:org.openengsb.openengsbplugin.Checkstyle.java

public static void insertCheckstyleConfigLocation(Document configuredPom, String profileXpath, File configFile)
        throws XPathExpressionException {
    Node node = configuredPom.createElementNS(POM_NS_URI, "configLocation");
    node.setTextContent(configFile.toURI().toString());

    Tools.insertDomNode(configuredPom, node,
            profileXpath + "/pom:build/pom:plugins/pom:plugin"
                    + "[pom:groupId='org.apache.maven.plugins' and pom:artifactId='maven-checkstyle-plugin']"
                    + "/pom:configuration",
            NS_CONTEXT);//from ww  w  .ja  v  a  2s .co m
}

From source file:org.openengsb.openengsbplugin.Eclipse.java

private void setCheckstyleEclipseConfigLocation(Document configuredPom, String profileXpath,
        String locationToInsert) throws XPathExpressionException {
    Node node = configuredPom.createElementNS(POM_NS_URI, "location");
    node.setTextContent(locationToInsert);

    String eclipsePluginXPath = profileXpath + "/pom:build/pom:plugins/pom:plugin"
            + "[pom:groupId='org.apache.maven.plugins' and pom:artifactId='maven-eclipse-plugin']";

    Tools.insertDomNode(configuredPom, node,
            eclipsePluginXPath + "/pom:configuration/pom:additionalConfig/pom:file", NS_CONTEXT);
}

From source file:org.openestate.io.openimmo.converters.OpenImmo_1_2_3.java

/**
 * Remove unsupported children from all &lt;flaechen&gt; elements.
 * <p>//from ww  w  .  ja  va2s  .c o  m
 * OpenImmo 1.2.2 does not support the following children for
 * &lt;flaechen&gt; elements: &lt;anzahl_balkone&gt;, &lt;anzahl_terrassen&gt;
 * <p>
 * These elements are removed by this function. If
 * &lt;anzahl_balkon_terrassen&gt; is not already specified, the sum values of
 * &lt;anzahl_balkone&gt; and &lt;anzahl_terrassen&gt; are written into
 * &lt;anzahl_balkon_terrassen&gt;.
 *
 * @param doc OpenImmo document in version 1.2.3
 * @throws JaxenException
 */
protected void downgradeFlaechenChildElements(Document doc) throws JaxenException {
    List nodes = XmlUtils.newXPath("/io:openimmo/io:anbieter/io:immobilie/io:flaechen", doc).selectNodes(doc);
    for (Object item : nodes) {
        Element parentNode = (Element) item;
        boolean passedAnzahlBalkone = false;
        boolean passedAnzahlTerrassen = false;
        double sum = 0;

        List childNodes = XmlUtils.newXPath("io:anzahl_balkone", doc).selectNodes(parentNode);
        for (Object childItem : childNodes) {
            Node node = (Node) childItem;
            if (!passedAnzahlBalkone) {
                passedAnzahlBalkone = true;
                String value = StringUtils.trimToNull(node.getTextContent());
                try {
                    sum += (value != null) ? Double.parseDouble(value) : 0;
                } catch (NumberFormatException ex) {
                    LOGGER.warn(
                            "Can't parse <anzahl_balkone>" + value + "</anzahl_balkone> into a numeric value!");
                    LOGGER.warn("> " + ex.getLocalizedMessage(), ex);
                }
            }
            parentNode.removeChild(node);
        }

        childNodes = XmlUtils.newXPath("io:anzahl_terrassen", doc).selectNodes(parentNode);
        for (Object childItem : childNodes) {
            Node node = (Node) childItem;
            if (!passedAnzahlTerrassen) {
                passedAnzahlTerrassen = true;
                String value = StringUtils.trimToNull(node.getTextContent());
                try {
                    sum += (value != null) ? Double.parseDouble(value) : 0;
                } catch (NumberFormatException ex) {
                    LOGGER.warn("Can't parse <anzahl_terrassen>" + value
                            + "</anzahl_terrassen> into a numeric value!");
                    LOGGER.warn("> " + ex.getLocalizedMessage(), ex);
                }
            }
            parentNode.removeChild(node);
        }

        if (sum > 0) {
            Element node = (Element) XmlUtils.newXPath("io:anzahl_balkon_terrassen", doc)
                    .selectSingleNode(parentNode);
            if (node == null) {
                node = doc.createElementNS(StringUtils.EMPTY, "anzahl_balkon_terrassen");
                node.setTextContent(String.valueOf(sum));
                parentNode.appendChild(node);
            } else if (StringUtils.isBlank(node.getTextContent())) {
                node.setTextContent(String.valueOf(sum));
            }
        }
    }
}

From source file:org.opens.tanaguru.crawler.util.HeritrixAttributeValueModifier.java

@Override
public Document modifyDocument(Document document, String value) {
    if (value == null || value.isEmpty()) {
        return document;
    }/*from   www . j a  va 2 s .co  m*/
    try {
        Node parentNode = getNodeFromXpath(document);
        NamedNodeMap attr = parentNode.getAttributes();
        Node nodeAttr = attr.getNamedItem(DEFAULT_ATTRIBUTE_NAME);
        if (StringUtils.isNotEmpty(value)) {
            nodeAttr.setTextContent(value);
        } else {
            parentNode.getParentNode().removeChild(parentNode);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Update " + getAttributeValue() + " attribute of bean " + getIdBeanParent()
                    + " with value " + value);
        }
    } catch (XPathExpressionException ex) {
        LOGGER.warn(ex);
    }
    return document;
}

From source file:org.peertrust.demo.common.InstallationSession.java

/**
 *Sets the text value of an rdf xml element. 
 * @param xmlPath -- specifies the xml element an the tex to set
 * @param rdfDocument -- the rdf document which wil be changed
 *///from w ww  .j  a v a  2 s.  c om
public void setTextValue(String[] xmlPath, Document rdfDocument) {
    if (xmlPath.length < 3) {
        return;
    } else {
        //get resource e.g pt:EntitiesTable
        NodeList nl = rdfDocument.getElementsByTagName(xmlPath[0]);
        Node node = null;
        for (int i = 0; i < 200; i++) {//<200 just to quit somewhen
            node = nl.item(i);//the resource definition which have a about property
            if (node == null) {
                break;
            } else {

                if (node.getAttributes().getNamedItem("rdf:about") != null) {
                    break;
                }
            }
        }
        if (node != null) {
            nl = node.getChildNodes();//getOwnerDocument().getElementsByTagName(xmlPath[1]);
            node = nl.item(0);
            //el.setNodeValue(xmlPath[2]);
            for (int i = 0; i < 200; i++) {//<200 just to quit somewhen
                node = nl.item(i);//the resource definition which have a about property
                if (node == null) {
                    break;
                } else {
                    String name = node.getNodeName();
                    //System.out.println("name:"+name+" "+xmlPath[1]);
                    if (name.equals(xmlPath[1])) {
                        break;
                    }
                }
            }

            node.setTextContent(xmlPath[2]);
        } else {
            //System.out.println("could not find:"+xmlPath);
        }
    }
}