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.kuali.rice.kns.workflow.attribute.KualiXmlAttributeHelper.java

/**
 * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
 * where the super class expects to see them, overwriting the original title in the XML.
 *
 * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
 *//*from   w ww  . j a v  a 2  s  . c  om*/

public Element processConfigXML(Element root, String[] xpathExpressionElements) {

    NodeList fields = root.getElementsByTagName("fieldDef");
    Element theTag = null;
    String docContent = "";

    /**
     * This section will check to see if document content has been defined in the configXML for the document type, by running an
     * XPath. If this is an empty list the xpath expression in the fieldDef is used to define the xml document content that is
     * added to the configXML. The xmldocument content is of this form, when in the document configXML. <xmlDocumentContent>
     * <org.kuali.rice.krad.bo.SourceAccountingLine> <amount> <value>%totaldollarAmount%</value> </amount>
     * </org.kuali.rice.krad.bo.SourceAccountingLine> </xmlDocumentContent> This class generates this on the fly, by creating an XML
     * element for each term in the XPath expression. When this doesn't apply XML can be coded in the configXML for the
     * ruleAttribute.
     *
     * @see org.kuali.rice.kew.plugin.attributes.WorkflowAttribute#getDocContent()
     */

    org.w3c.dom.Document xmlDoc = null;
    if (!xmlDocumentContentExists(root)) { // XML Document content is given because the xpath is non standard
        fields = root.getElementsByTagName("fieldDef");
        xmlDoc = root.getOwnerDocument();
    }
    for (int i = 0; i < fields.getLength(); i++) { // loop over each fieldDef
        String name = null;
        if (!xmlDocumentContentExists(root)) {
            theTag = (Element) fields.item(i);

            /*
             * Even though there may be multiple xpath test, for example one for source lines and one for target lines, the
             * xmlDocumentContent only needs one, since it is used for formatting. The first one is arbitrarily selected, since
             * they are virtually equivalent in structure, most of the time.
             */

            List<String> xPathTerms = getXPathTerms(theTag);
            if (xPathTerms.size() != 0) {
                Node iterNode = xmlDoc.createElement("xmlDocumentContent");

                xmlDoc.normalize();

                iterNode.normalize();

                /*
                 * Since this method is run once per attribute and there may be multiple fieldDefs, the first fieldDef is used
                 * to create the configXML.
                 */
                for (int j = 0; j < xPathTerms.size(); j++) {// build the configXML based on the Xpath
                    // TODO - Fix the document content element generation
                    iterNode.appendChild(xmlDoc.createElement(xPathTerms.get(j)));
                    xmlDoc.normalize();

                    iterNode = iterNode.getFirstChild();
                    iterNode.normalize();

                }
                iterNode.setTextContent("%" + xPathTerms.get(xPathTerms.size() - 1) + "%");
                root.appendChild(iterNode);
            }
        }
        theTag = (Element) fields.item(i);
        // check to see if a values finder is being used to set valid values for a field
        NodeList displayTagElements = theTag.getElementsByTagName("display");
        if (displayTagElements.getLength() == 1) {
            Element displayTag = (Element) displayTagElements.item(0);
            List valuesElementsToAdd = new ArrayList();
            for (int w = 0; w < displayTag.getChildNodes().getLength(); w++) {
                Node displayTagChildNode = (Node) displayTag.getChildNodes().item(w);
                if ((displayTagChildNode != null) && ("values".equals(displayTagChildNode.getNodeName()))) {
                    if (displayTagChildNode.getChildNodes().getLength() > 0) {
                        String valuesNodeText = displayTagChildNode.getFirstChild().getNodeValue();
                        String potentialClassName = getPotentialKualiClassName(valuesNodeText,
                                KUALI_VALUES_FINDER_REFERENCE_PREFIX, KUALI_VALUES_FINDER_REFERENCE_SUFFIX);
                        if (StringUtils.isNotBlank(potentialClassName)) {
                            try {
                                Class finderClass = Class.forName((String) potentialClassName);
                                KeyValuesFinder finder = (KeyValuesFinder) finderClass.newInstance();
                                NamedNodeMap valuesNodeAttributes = displayTagChildNode.getAttributes();
                                Node potentialSelectedAttribute = (valuesNodeAttributes != null)
                                        ? valuesNodeAttributes.getNamedItem("selected")
                                        : null;
                                for (Iterator iter = finder.getKeyValues().iterator(); iter.hasNext();) {
                                    KeyValue keyValue = (KeyValue) iter.next();
                                    Element newValuesElement = root.getOwnerDocument().createElement("values");
                                    newValuesElement.appendChild(
                                            root.getOwnerDocument().createTextNode(keyValue.getKey()));
                                    // newValuesElement.setNodeValue(KeyValue.getKey().toString());
                                    newValuesElement.setAttribute("title", keyValue.getValue());
                                    if (potentialSelectedAttribute != null) {
                                        newValuesElement.setAttribute("selected",
                                                potentialSelectedAttribute.getNodeValue());
                                    }
                                    valuesElementsToAdd.add(newValuesElement);
                                }
                            } catch (ClassNotFoundException cnfe) {
                                String errorMessage = "Caught an exception trying to find class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, cnfe);
                                throw new RuntimeException(errorMessage, cnfe);
                            } catch (InstantiationException ie) {
                                String errorMessage = "Caught an exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, ie);
                                throw new RuntimeException(errorMessage, ie);
                            } catch (IllegalAccessException iae) {
                                String errorMessage = "Caught an access exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, iae);
                                throw new RuntimeException(errorMessage, iae);
                            }
                        } else {
                            valuesElementsToAdd.add(displayTagChildNode.cloneNode(true));
                        }
                        displayTag.removeChild(displayTagChildNode);
                    }
                }
            }
            for (Iterator iter = valuesElementsToAdd.iterator(); iter.hasNext();) {
                Element valuesElementToAdd = (Element) iter.next();
                displayTag.appendChild(valuesElementToAdd);
            }
        }
        if ((xpathExpressionElements != null) && (xpathExpressionElements.length > 0)) {
            NodeList fieldEvaluationElements = theTag.getElementsByTagName("fieldEvaluation");
            if (fieldEvaluationElements.getLength() == 1) {
                Element fieldEvaluationTag = (Element) fieldEvaluationElements.item(0);
                List tagsToAdd = new ArrayList();
                for (int w = 0; w < fieldEvaluationTag.getChildNodes().getLength(); w++) {
                    Node fieldEvaluationChildNode = (Node) fieldEvaluationTag.getChildNodes().item(w);
                    Element newTagToAdd = null;
                    if ((fieldEvaluationChildNode != null)
                            && ("xpathexpression".equals(fieldEvaluationChildNode.getNodeName()))) {
                        newTagToAdd = root.getOwnerDocument().createElement("xpathexpression");
                        newTagToAdd.appendChild(root.getOwnerDocument()
                                .createTextNode(generateNewXpathExpression(
                                        fieldEvaluationChildNode.getFirstChild().getNodeValue(),
                                        xpathExpressionElements)));
                        tagsToAdd.add(newTagToAdd);
                        fieldEvaluationTag.removeChild(fieldEvaluationChildNode);
                    }
                }
                for (Iterator iter = tagsToAdd.iterator(); iter.hasNext();) {
                    Element elementToAdd = (Element) iter.next();
                    fieldEvaluationTag.appendChild(elementToAdd);
                }
            }
        }
        theTag.setAttribute("title", getBusinessObjectTitle(theTag));

    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(XmlJotter.jotNode(root));
        StringWriter xmlBuffer = new StringWriter();
        try {

            root.normalize();
            Source source = new DOMSource(root);
            Result result = new StreamResult(xmlBuffer);
            TransformerFactory.newInstance().newTransformer().transform(source, result);
        } catch (Exception e) {
            LOG.debug(" Exception when printing debug XML output " + e);
        }
        LOG.debug(xmlBuffer.getBuffer());
    }

    return root;
}

From source file:org.linguafranca.pwdb.kdbx.dom.DomSerializableDatabase.java

public static DomSerializableDatabase createEmptyDatabase() throws IOException {
    DomSerializableDatabase result = new DomSerializableDatabase();
    // read in the template KeePass XML database
    result.load(result.getClass().getClassLoader().getResourceAsStream("base.kdbx.xml"));
    try {//from  www.  j a  v a  2  s .  c om
        // replace all placeholder dates with now
        String now = DomHelper.dateFormatter.format(new Date());
        NodeList list = (NodeList) DomHelper.xpath.evaluate("//*[contains(text(),'${creationDate}')]",
                result.doc.getDocumentElement(), XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i++) {
            list.item(i).setTextContent(now);
        }
        // set the root group UUID
        Node uuid = (Node) DomHelper.xpath.evaluate("//" + DomHelper.UUID_ELEMENT_NAME,
                result.doc.getDocumentElement(), XPathConstants.NODE);
        uuid.setTextContent(DomHelper.base64RandomUuid());
    } catch (XPathExpressionException e) {
        throw new IllegalStateException(e);
    }
    result.setEncryption(new Salsa20StreamEncryptor(SecureRandom.getSeed(32)));
    return result;
}

From source file:org.mycontroller.standalone.api.XmlApi.java

public void update(String uri, String xpath, String value) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
    Document document = getDocument(uri);
    XPathExpression expression = getXPathExpression(xpath);
    Node node = (Node) expression.evaluate(document, XPathConstants.NODE);
    node.setTextContent(value);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(new DOMSource(document), new StreamResult(FileUtils.getFile(uri)));
}

From source file:org.odk.collect.android.logic.FormRelationsManager.java

/**
 * Modifies the parent form if a paired node with child form is changed.
 *
 * When this method is called, both child and parent instance are saved to
 * disk. After opening each file, this method gets all node pairs, or
 * mappings, and loops through them. For each mapping, the instance value
 * is obtained in both files. If there is a difference, then the parent
 * is modified in memory. If there is any change in the parent, then the
 * file is rewritten to disk. If there is an exception while evaulating
 * xpaths or doing anything else, updating the parent form is aborted.
 *
 * If the parent form is changed, then its status is changed to
 * incomplete./*w w w.  jav a  2s.  c  o m*/
 *
 * @param childId Instance id
 * @return Returns -1 if no parent, 0 if has parent, but no updates, 1 if
 * has parent and updates made.
 */
private static int manageParentForm(long childId) {
    Long parentId = FormRelationsDb.getParent(childId);
    if (LOCAL_LOG) {
        Log.d(TAG, "Inside manageParentForm. Parent instance id is \'" + parentId + "\'");
    }
    if (parentId < 0) { // No parent form to manage
        return -1;
    }

    int returnCode = 0;

    try {
        String parentInstancePath = getInstancePath(getInstanceUriFromId(parentId));
        String childInstancePath = getInstancePath(getInstanceUriFromId(childId));

        Document parentDocument = getDocument(parentInstancePath);
        Document childDocument = getDocument(childInstancePath);

        XPath xpath = XPathFactory.newInstance().newXPath();
        ArrayList<MappingData> mappings = FormRelationsDb.getMappingsToParent(childId);
        boolean editedParentForm = false;
        mUseLog = new UseLog(parentInstancePath, true);
        for (MappingData mapping : mappings) {
            XPathExpression parentExpression = xpath.compile(mapping.parentNode);
            XPathExpression childExpression = xpath.compile(mapping.childNode);

            Node parentNode = (Node) parentExpression.evaluate(parentDocument, XPathConstants.NODE);
            Node childNode = (Node) childExpression.evaluate(childDocument, XPathConstants.NODE);

            if (null == parentNode || null == childNode) {
                throw new FormRelationsException(BAD_XPATH_INSTANCE,
                        "Child: " + mapping.childNode + ", Parent: " + mapping.parentNode);
            }

            if (!childNode.getTextContent().equals(parentNode.getTextContent())) {
                mUseLog.log(UseLogContract.RELATION_CHANGE_VALUE, parentId, mapping.parentNode,
                        childNode.getTextContent());

                Log.i(TAG,
                        "Found difference updating parent form @ parent node \'" + parentNode.getNodeName()
                                + "\'. Child: \'" + childNode.getTextContent() + "\' <> Parent: \'"
                                + parentNode.getTextContent() + "\'");
                parentNode.setTextContent(childNode.getTextContent());
                editedParentForm = true;
            }
        }

        if (editedParentForm) {
            writeDocumentToFile(parentDocument, parentInstancePath);
            mUseLog.writeBackLogAndClose();
            ContentValues cv = new ContentValues();
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
            Collect.getInstance().getContentResolver().update(getInstanceUriFromId(parentId), cv, null, null);
            returnCode = 1;
        }
    } catch (FormRelationsException e) {
        if (e.getErrorCode() == PROVIDER_NO_INSTANCE) {
            Log.w(TAG, "Unable to find the instance path for either this form (id=" + childId
                    + ") or its parent (id=" + parentId + ")");
        } else if (e.getErrorCode() == BAD_XPATH_INSTANCE) {
            Log.w(TAG, "Bad XPath from one of child or parent. " + e.getInfo());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    return returnCode;
}

From source file:org.odk.collect.android.logic.FormRelationsManager.java

/**
 * Inserts data into child form from one morsel of traversal data.
 *
 * @param td A `saveInstance` morsel of traversal data.
 * @param document The child form represented as a document.
 * @return Returns true if and only if the child instance is modified.
 * @throws XPathExpressionException Another possible error that should
 * abort this routine./*w w w. ja va2 s  . c  o  m*/
 * @throws FormRelationsException Thrown if the xpath data for the child
 * form is bad.
 */
private static boolean insertIntoChild(TraverseData td, Document document)
        throws XPathExpressionException, FormRelationsException {
    boolean isModified = false;
    String childInstanceValue = td.instanceValue;
    if (null != childInstanceValue) {
        // extract nodes using xpath
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expression;

        String childInstanceXpath = td.attrValue;

        expression = xpath.compile(childInstanceXpath);
        Node node = (Node) expression.evaluate(document, XPathConstants.NODE);
        if (null == node) {
            throw new FormRelationsException(BAD_XPATH_INSTANCE, childInstanceXpath);
        }
        if (!node.getTextContent().equals(childInstanceValue)) {
            Log.v(TAG, "Found difference saving child form @ child node \'" + node.getNodeName()
                    + "\'. Child: \'" + node.getTextContent() + "\' <> Parent: \'" + childInstanceValue + "\'");
            node.setTextContent(childInstanceValue);
            isModified = true;
        }
    }
    return isModified;
}

From source file:org.ojbc.intermediaries.sn.notification.NotificationProcessorTest.java

@Test
public void testNotificationWithWhitelistFilterEnhancementStrategy() throws Exception {

    File notificationMessageFile = new File("src/test/resources/xmlInstances/notificationMessage.xml");
    Document notificationMessageDocument = XmlUtils.parseFileToDocument(notificationMessageFile);
    Node sidElement = XmlUtils.xPathNodeSearch(notificationMessageDocument,
            "//notfm-exch:NotificationMessage/jxdm41:Person[1]/jxdm41:PersonAugmentation/jxdm41:PersonStateFingerprintIdentification/nc:IdentificationID");
    sidElement.setTextContent("A5008305");

    Exchange e = new DefaultExchange((CamelContext) null);
    Message inMessage = e.getIn();//ww  w  .j a  va  2  s. c o m
    inMessage.setBody(notificationMessageDocument);

    WhitelistFilteringEmailEnhancementStrategy d = new WhitelistFilteringEmailEnhancementStrategy();
    d.addAddressToWhitelist("po1@localhost");

    notificationProcessor.setEmailEnhancementStrategy(d);

    notificationProcessor.findSubscriptionsForNotification(e);

    // this mimics the component of the Camel route that splits the notifications

    @SuppressWarnings("unchecked")
    List<EmailNotification> emailNotifications = (List<EmailNotification>) e.getIn()
            .getHeader(NotificationConstants.HEADER_EMAIL_NOTIFICATIONS);
    assertEquals(2, emailNotifications.size());

    boolean foundPO1 = false;
    boolean foundPO3Blocked = false;

    for (EmailNotification notification : emailNotifications) {
        // set things up like happens in the processor...this is a consequence of segmenting the logic across camel route and processor
        e.getIn().setBody(notification);
        e.getIn().setHeader(NotificationConstants.HEADER_NOTIFICATION_TOPIC, "");
        notificationProcessor.createNotificationEmail(e);
        String toAddys = (String) e.getOut().getHeader(NotificationConstants.HEADER_TO);
        if (toAddys == null) {
            @SuppressWarnings("unchecked")
            Set<String> blockedAddressees = (Set<String>) e.getOut()
                    .getHeader(NotificationConstants.HEADER_BLOCKED);
            assertNotNull(blockedAddressees);
            foundPO3Blocked = blockedAddressees.contains("po3@localhost");
        } else if (toAddys.equals("po1@localhost")) {
            foundPO1 = true;
        }
    }

    assertTrue(foundPO1);
    assertTrue(foundPO3Blocked);

}

From source file:org.ojbc.intermediaries.sn.notification.NotificationProcessorTest.java

@Test
public void testNotificationWithFilter() throws Exception {

    File notificationMessageFile = new File("src/test/resources/xmlInstances/notificationMessage.xml");
    Document notificationMessageDocument = XmlUtils.parseFileToDocument(notificationMessageFile);
    Node sidElement = XmlUtils.xPathNodeSearch(notificationMessageDocument,
            "//notfm-exch:NotificationMessage/jxdm41:Person[1]/jxdm41:PersonAugmentation/jxdm41:PersonStateFingerprintIdentification/nc:IdentificationID");
    sidElement.setTextContent("A5008305"); // a sid that has a subscription

    Exchange e = new DefaultExchange((CamelContext) null);
    Message inMessage = e.getIn();/*from w  ww .j  av a  2 s . c  o  m*/
    inMessage.setBody(notificationMessageDocument);

    notificationProcessor.findSubscriptionsForNotification(e);

    assertNull(e.getProperty(Exchange.ROUTE_STOP));

    notificationProcessor.setNotificationFilterStrategy(new NotificationFilterStrategy() {
        @Override
        public boolean shouldMessageBeFiltered(NotificationRequest nr) {
            return true;
        }
    });

    notificationProcessor.findSubscriptionsForNotification(e);
    assertEquals(Boolean.TRUE, e.getProperty(Exchange.ROUTE_STOP));

}

From source file:org.ojbc.intermediaries.sn.notification.NotificationProcessorTest.java

@Test
public void testNotificationWithNoSubscription() throws Exception {

    File notificationMessageFile = new File("src/test/resources/xmlInstances/notificationMessage.xml");
    Document notificationMessageDocument = XmlUtils.parseFileToDocument(notificationMessageFile);

    Node sidElement = XmlUtils.xPathNodeSearch(notificationMessageDocument,
            "//notfm-exch:NotificationMessage/jxdm41:Person[1]/jxdm41:PersonAugmentation/jxdm41:PersonStateFingerprintIdentification/nc:IdentificationID");
    sidElement.setTextContent("XXXXXXX"); // a sid that doesn't have a subscription

    Exchange e = new DefaultExchange((CamelContext) null);
    Message inMessage = e.getIn();/*  w  w  w .  ja  va  2  s  .c o m*/
    inMessage.setBody(notificationMessageDocument);

    notificationProcessor.findSubscriptionsForNotification(e);

    assertEquals(Boolean.TRUE, e.getProperty(Exchange.ROUTE_STOP));

}

From source file:org.ojbc.intermediaries.sn.tests.AbstractSubscriptionNotificationIntegrationTest.java

protected List<WiserMessage> notify(String notificationFileName, String activityDateTimeXpath)
        throws ParserConfigurationException, SAXException, IOException, Exception {
    File inputFile = new File("src/test/resources/xmlInstances/" + notificationFileName);

    DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory.newInstance();
    docBuilderFact.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFact.newDocumentBuilder();
    Document notificationDom = docBuilder.parse(inputFile);

    Node dateTimeNode = XmlUtils.xPathNodeSearch(notificationDom, activityDateTimeXpath + "/nc:Date");
    dateTimeNode.setTextContent(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    String notificationBody = OJBUtils.getStringFromDocument(notificationDom);

    Wiser wiser = new Wiser();
    wiser.setPort(mailPort);/*  w  ww .  j  a v  a  2 s .c  om*/
    wiser.setHostname(mailServerName);
    wiser.start();

    List<WiserMessage> messages = new ArrayList<WiserMessage>();

    try {

        HttpUtils.post(notificationBody, notificationBrokerUrl);
        Thread.sleep(MAIL_READ_DELAY);

        messages = wiser.getMessages();

    } finally {
        wiser.stop();
    }

    return messages;

}

From source file:org.opendaylight.aaa.cert.impl.CertificateManagerService.java

private void updateCertManagerSrvConfig(String ctlPwd, String trustPwd) {
    try {/* w  w w  .  ja va  2s  .  co m*/
        LOG.debug("Update Certificate manager service config file");
        final File configFile = new File(DEFAULT_CONFIG_FILE_PATH);
        if (configFile.exists()) {
            final String storePwdTag = "store-password";
            final String ctlStoreTag = "ctlKeystore";
            final String trustStoreTag = "trustKeystore";
            final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            final Document doc = docBuilder.parse(configFile);
            final NodeList ndList = doc.getElementsByTagName(storePwdTag);
            for (int i = 0; i < ndList.getLength(); i++) {
                final Node nd = ndList.item(i);
                if (nd.getParentNode() != null && nd.getParentNode().getNodeName().equals(ctlStoreTag)) {
                    nd.setTextContent(ctlPwd);
                } else if (nd.getParentNode() != null
                        && nd.getParentNode().getNodeName().equals(trustStoreTag)) {
                    nd.setTextContent(trustPwd);
                }
            }
            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 Certificate manager service config file does not exist {}", DEFAULT_CONFIG_FILE_PATH);
        }
    } catch (ParserConfigurationException | TransformerException | SAXException | IOException e) {
        LOG.error("Error while updating Certificate manager service config file", e);
    }
}