Example usage for org.w3c.dom Node getTextContent

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

Introduction

In this page you can find the example usage for org.w3c.dom Node getTextContent.

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

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

Usage

From source file:com.temenos.useragent.generic.mediatype.AtomXmlContentHandlerTest.java

@Test
public void testSetAddingNewElementAtLevelZero() {
    xmlContentHandler.setValue("text-2", "text2");
    NodeList text2Nodes = document.getElementsByTagNameNS(NS_ODATA, "text-2");
    assertEquals(1, text2Nodes.getLength());
    Node text2Node = text2Nodes.item(0);
    assertEquals("text2", text2Node.getTextContent());
    assertEquals(0, text2Node.getAttributes().getLength());
}

From source file:com.temenos.useragent.generic.mediatype.AtomXmlContentHandlerTest.java

@Test
public void testSetingExistingElementAtLevelZero() {
    xmlContentHandler.setValue("text-1", "text1");
    NodeList text1Nodes = document.getElementsByTagNameNS(NS_ODATA, "text-1");
    assertEquals(1, text1Nodes.getLength());
    Node text1Node1 = text1Nodes.item(0);
    assertEquals("text1", text1Node1.getTextContent());
    assertEquals(0, text1Node1.getAttributes().getLength());
}

From source file:me.willowcheng.makerthings.model.OpenHABItem.java

public OpenHABItem(Node startNode) {
    if (startNode.hasChildNodes()) {
        NodeList childNodes = startNode.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeName().equals("type")) {
                this.setType(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("name")) {
                this.setName(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("state")) {
                if (childNode.getTextContent().equals("Uninitialized")) {
                    this.setState(null);
                } else {
                    this.setState(childNode.getTextContent());
                }/*w w w. j  a  v a2s. c o m*/
            } else if (childNode.getNodeName().equals("link")) {
                this.setLink(childNode.getTextContent());
            }
        }
    }
}

From source file:forge.quest.io.QuestDataIO.java

/**
 * <p>/*  w w  w  .j a v a 2  s.  c  o  m*/
 * updateSaveFile.
 * </p>
 *
 * @param newData
 *            a {@link forge.quest.data.QuestData} object.
 * @param input
 *            a {@link java.lang.String} object.
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 * @throws NoSuchFieldException
 * @throws IllegalAccessException
 */
private static void updateSaveFile(final QuestData newData, final String input, String filename)
        throws ParserConfigurationException, SAXException, IOException, IllegalAccessException,
        NoSuchFieldException {
    final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(input));
    final Document document = builder.parse(is);

    final int saveVersion = newData.getVersionNumber();

    if (saveVersion < 3) {
        QuestDataIO.setFinalField(QuestData.class, "assets", newData, new QuestAssets(null));

        final int diffIdx = Integer
                .parseInt(document.getElementsByTagName("diffIndex").item(0).getTextContent());
        QuestDataIO.setFinalField(QuestData.class, "achievements", newData, new QuestAchievements(diffIdx));
    }

    if (saveVersion < 4) {
        QuestDataIO.setFinalField(QuestAssets.class, "inventoryItems", newData.getAssets(),
                new EnumMap<QuestItemType, Integer>(QuestItemType.class));
    }

    if (saveVersion < 5) {
        QuestDataIO.setFinalField(QuestAssets.class, "combatPets", newData.getAssets(),
                new HashMap<String, QuestItemCondition>());
    }

    if (saveVersion < 6) {
        QuestDataIO.setFinalField(QuestData.class, "petSlots", newData, new HashMap<>());
    }

    if (saveVersion < 8) {
        QuestDataIO.setFinalField(QuestData.class, "isCharmActive", newData, false);
    }

    final QuestAssets qS = newData.getAssets();
    final QuestAchievements qA = newData.getAchievements();

    switch (saveVersion) {
    // There should be a fall-through between the cases so that each
    // version's changes get applied progressively
    case 0:
        // First beta release with new file format,
        // inventory needs to be migrated
        QuestDataIO.setFinalField(QuestAssets.class, "inventoryItems", newData.getAssets(),
                new EnumMap<QuestItemType, Integer>(QuestItemType.class));
        qS.setItemLevel(QuestItemType.ESTATES,
                Integer.parseInt(document.getElementsByTagName("estatesLevel").item(0).getTextContent()));
        qS.setItemLevel(QuestItemType.LUCKY_COIN,
                Integer.parseInt(document.getElementsByTagName("luckyCoinLevel").item(0).getTextContent()));
        qS.setItemLevel(QuestItemType.SLEIGHT,
                Integer.parseInt(document.getElementsByTagName("sleightOfHandLevel").item(0).getTextContent()));

        final int gearLevel = Integer
                .parseInt(document.getElementsByTagName("gearLevel").item(0).getTextContent());
        if (gearLevel >= 1) {
            newData.getAssets().setItemLevel(QuestItemType.MAP, 1);
        }
        if (gearLevel == 2) {
            newData.getAssets().setItemLevel(QuestItemType.ZEPPELIN, 1);
        }
        //$FALL-THROUGH$
    case 1:
        // nothing to do here, everything is managed by CardPoolToXml
        // deserializer

    case 2:
        // questdata was divided into assets and achievements
        if (StringUtils.isBlank(newData.getName())) {
            QuestDataIO.setFinalField(QuestData.class, "name", newData, filename);
        }

        QuestDataIO.setFinalField(QuestAchievements.class, "win", qA,
                Integer.parseInt(document.getElementsByTagName("win").item(0).getTextContent()));
        QuestDataIO.setFinalField(QuestAchievements.class, "lost", qA,
                Integer.parseInt(document.getElementsByTagName("lost").item(0).getTextContent()));

        Node nw;
        if ((nw = document.getElementsByTagName("winstreakBest").item(0)) != null) {
            QuestDataIO.setFinalField(QuestAchievements.class, "winstreakBest", qA,
                    Integer.parseInt(nw.getTextContent()));
        }
        if ((nw = document.getElementsByTagName("winstreakCurrent").item(0)) != null) {
            QuestDataIO.setFinalField(QuestAchievements.class, "winstreakCurrent", qA,
                    Integer.parseInt(nw.getTextContent()));
        }

        QuestDataIO.setFinalField(QuestAchievements.class, "challengesPlayed", qA,
                Integer.parseInt(document.getElementsByTagName("challengesPlayed").item(0).getTextContent()));

        final List<Integer> completedChallenges = new ArrayList<>();
        QuestDataIO.setFinalField(QuestAchievements.class, "completedChallenges", qA, completedChallenges);

        if ((nw = document.getElementsByTagName("completedChallenges").item(0)) != null) {
            final NodeList ccs = nw.getChildNodes();
            for (int iN = 0; iN < ccs.getLength(); iN++) {
                final Node n0 = ccs.item(iN);
                if (n0.getNodeType() != Node.ELEMENT_NODE) {
                    continue;
                }
                completedChallenges.add(Integer.parseInt(n0.getTextContent()));
            }
        }

        final XStream xs = QuestDataIO.getSerializer(true);

        QuestDataIO.setFinalField(QuestAssets.class, "credits", qS,
                Integer.parseInt(document.getElementsByTagName("credits").item(0).getTextContent()));
        QuestDataIO.setFinalField(QuestAssets.class, "cardPool", qS,
                QuestDataIO.readAsset(xs, document, "cardPool", ItemPool.class));
        QuestDataIO.setFinalField(QuestAssets.class, "myDecks", qS,
                QuestDataIO.readAsset(xs, document, "myDecks", HashMap.class));
        QuestDataIO.setFinalField(QuestAssets.class, "shopList", qS,
                QuestDataIO.readAsset(xs, document, "shopList", ItemPool.class));
        QuestDataIO.setFinalField(QuestAssets.class, "newCardList", qS,
                QuestDataIO.readAsset(xs, document, "newCardList", ItemPool.class));

        //$FALL-THROUGH$
    case 3:
        // QuestInventory class no longer exists - KV pairs of
        // QuestItemPair => level moved to assets
        final Node oldInventory = saveVersion > 0 ? document.getElementsByTagName("inventory").item(1) : null;
        if (null != oldInventory) {
            for (int iN = 0; iN < oldInventory.getChildNodes().getLength(); iN++) {
                final Node _n = oldInventory.getChildNodes().item(iN);
                if (_n.getNodeType() != Node.ELEMENT_NODE) {
                    continue;
                }
                final Element n = (Element) _n;
                final String name = n.getElementsByTagName("string").item(0).getTextContent();
                final QuestItemType qType = QuestItemType.valueFromSaveKey(name);
                int level = 0;
                for (int iX = 0; iX < n.getChildNodes().getLength(); iX++) {
                    final Node _x = n.getChildNodes().item(iX);
                    if (_x.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    final Element x = (Element) _x;
                    if (!x.getTagName().startsWith("forge.quest.data.")) {
                        continue;
                    }
                    final String sLevel = x.getElementsByTagName("level").item(0).getTextContent();
                    if (StringUtils.isNotBlank(sLevel)) {
                        level = Integer.parseInt(sLevel);
                    }
                }
                qS.setItemLevel(qType, level);
            }
        }

        //$FALL-THROUGH$
    case 4:
        if (saveVersion > 0) {
            NodeList pets = document.getElementsByTagName("pets").item(0).getChildNodes();
            for (int i = 0; i < pets.getLength(); i++) {
                if (pets.item(i).getNodeType() != Node.ELEMENT_NODE) {
                    continue;
                }
                final Element entry = (Element) pets.item(i);
                String name = entry.getElementsByTagName("string").item(0).getTextContent();
                String sLevel = entry.getElementsByTagName("level").item(0).getTextContent();
                qS.setPetLevel(name, Integer.parseInt(sLevel));
            }

        }

        // pet manager will be re-engineered here
        //$FALL-THROUGH$
    case 5:
    case 6:
        // have to convert completed challenges list members to strings.
        for (int i = qA.getLockedChallenges().size() - 1; i >= 0; i--) {
            Object lc = qA.getLockedChallenges().get(i);
            if (lc != null) {
                qA.getLockedChallenges().set(i, lc.toString());
            }
        }
        for (int i = qA.getCurrentChallenges().size() - 1; i >= 0; i--) {
            Object lc = qA.getCurrentChallenges().get(i);
            if (lc != null) {
                qA.getCurrentChallenges().set(i, lc.toString());
            }
        }

        //$FALL-THROUGH$
    case 7:
    case 8:
        QuestDataIO.setFinalField(QuestAssets.class, "draftDecks", qS, new HashMap<String, DeckGroup>());
        break;
    }

    // mark the QD as the latest version
    newData.setVersionNumber(QuestData.CURRENT_VERSION_NUMBER);

}

From source file:org.hdiv.config.xml.EditableValidationsBeanDefinitionParser.java

/**
 * Initialize Map with url and ValidationRule data.
 * /*  www . jav  a2 s.  com*/
 * @param node
 *            processing xml node
 * @param bean
 *            bean configuration
 * @param map
 *            Map with url and ValidationRule data
 */
private void processValidationRule(Node node, BeanDefinitionBuilder bean, Map map) {

    String value = node.getTextContent();
    List ids = this.convertToList(value);

    NamedNodeMap attributes = node.getAttributes();
    String url = attributes.getNamedItem("url").getTextContent();

    boolean enableDefaults = false;
    String enableDefaultsVal = attributes.getNamedItem("enableDefaults").getTextContent();
    if (enableDefaultsVal != null) {
        enableDefaults = Boolean.TRUE.toString().equalsIgnoreCase(enableDefaultsVal);
    }
    if (enableDefaults) {
        // Add defaults
        ids.addAll(this.defaultValidationIds);
    }

    map.put(url, ids);

}

From source file:me.willowcheng.makerthings.model.OpenHABSitemap.java

public OpenHABSitemap(Node startNode) {
    if (startNode.hasChildNodes()) {
        NodeList childNodes = startNode.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeName().equals("name")) {
                this.setName(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("label")) {
                this.setLabel(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("link")) {
                this.setLink(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("icon")) {
                this.setIcon(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("homepage")) {
                if (childNode.hasChildNodes()) {
                    NodeList homepageNodes = childNode.getChildNodes();
                    for (int j = 0; j < homepageNodes.getLength(); j++) {
                        Node homepageChildNode = homepageNodes.item(j);
                        if (homepageChildNode.getNodeName().equals("link")) {
                            this.setHomepageLink(homepageChildNode.getTextContent());
                        } else if (homepageChildNode.getNodeName().equals("leaf")) {
                            if (homepageChildNode.getTextContent().equals("true")) {
                                setLeaf(true);
                            } else {
                                setLeaf(false);
                            }/*from www.  j a  v a 2 s  . co m*/
                        }
                    }
                }
            }
        }
    }
}

From source file:com.googlecode.ehcache.annotations.config.EhCacheConfigBeanDefinitionParserTest.java

/**
 * Validate an evict-expired-elements Element with a single include element.
 *//* w w  w  .j a va 2  s .c om*/
@Test
public void testParseEvictExpiredSingleInclude() {
    Node nameAttribute = EasyMock.createMock(Node.class);
    EasyMock.expect(nameAttribute.getTextContent()).andReturn("foo");
    NamedNodeMap includeAttributes = EasyMock.createMock(NamedNodeMap.class);
    EasyMock.expect(includeAttributes.getNamedItem(EhCacheConfigBeanDefinitionParser.XSD_ATTRIBUTE__NAME))
            .andReturn(nameAttribute);

    Node includeNode = EasyMock.createMock(Node.class);
    EasyMock.expect(includeNode.getNodeType()).andReturn(Node.ELEMENT_NODE);
    EasyMock.expect(includeNode.getLocalName()).andReturn("include");
    EasyMock.expect(includeNode.getAttributes()).andReturn(includeAttributes);

    NodeList childNodes = EasyMock.createMock(NodeList.class);
    EasyMock.expect(childNodes.getLength()).andReturn(1);
    EasyMock.expect(childNodes.item(0)).andReturn(includeNode);

    Element evictExpired = EasyMock.createMock(Element.class);
    EasyMock.expect(evictExpired.getChildNodes()).andReturn(childNodes);
    EasyMock.replay(nameAttribute, includeAttributes, includeNode, childNodes, evictExpired);

    EhCacheConfigBeanDefinitionParser parser = new EhCacheConfigBeanDefinitionParser();
    List<CacheNameMatcher> matchers = parser.parseEvictExpiredElement(evictExpired);
    Assert.assertNotNull(matchers);
    Assert.assertEquals(1, matchers.size());
    CacheNameMatcher matcher = matchers.get(0);
    Assert.assertTrue(matcher instanceof ExactCacheNameMatcherImpl);
    ExactCacheNameMatcherImpl casted = (ExactCacheNameMatcherImpl) matcher;
    Assert.assertEquals("foo", casted.getName());

    EasyMock.verify(nameAttribute, includeAttributes, includeNode, childNodes, evictExpired);
}

From source file:com.diversityarrays.dalclient.DalUtil.java

/**
 * <p>/*from   w  w  w.j  ava  2s. c o m*/
 * Extract the &lt;Error Message="..." /&gt; from the XML response.
 * In fact it will retrieve all of the attributes from the 'Error' element
 * because some DAL responses use the attribute name as part of the message!
 * <p>
 * Note that if the Message attribute is missing, this will still produce
 * an error so it is <b>not</b> the same as just calling:
 * <code>
 * getElementAttributeValue(doc, "Error", "Message");
 * </code>
 * <br>
 * Any other attributes of the <i>Error</i> element will also be returned. This caters
 * for diagnostic errors which are returned by some of the DAL "update" operations.
 * @param doc
 * @return error message as a String or null
 */
static public String getXmlDalErrorMessage(Document doc) {
    String result = null;
    NodeList errorElements = doc.getElementsByTagName(DALClient.TAG_ERROR);
    if (errorElements.getLength() > 0) {
        Node item = errorElements.item(0);
        NamedNodeMap attributes = item.getAttributes();
        if (attributes == null) {
            result = String.format("No attributes available in '%s' element", //$NON-NLS-1$
                    DALClient.TAG_ERROR);
        } else {
            // We will get them *all*.
            StringBuilder sb = new StringBuilder();
            String sep = ""; //$NON-NLS-1$
            int nAttributes = attributes.getLength();
            for (int ai = 0; ai < nAttributes; ++ai) {
                Node attr = attributes.item(ai);
                if (attr != null) {
                    sb.append(sep).append(attr.getNodeName()).append('=').append(attr.getTextContent());
                    sep = ", "; //$NON-NLS-1$
                }
            }
            result = sb.toString();
        }
    }
    return result;
}

From source file:com.googlecode.ehcache.annotations.config.EhCacheConfigBeanDefinitionParserTest.java

/**
 * Validate an evict-expired-elements Element with a single exclude element.
 * Presence of exclude element will prepend a Include All matcher to the front of the list.
 *//*  w ww.j  a  va 2s  .  c o  m*/
@Test
public void testParseEvictExpiredSingleExclude() {
    Node nameAttribute = EasyMock.createMock(Node.class);
    EasyMock.expect(nameAttribute.getTextContent()).andReturn("foo");
    NamedNodeMap excludeAttributes = EasyMock.createMock(NamedNodeMap.class);
    EasyMock.expect(excludeAttributes.getNamedItem(EhCacheConfigBeanDefinitionParser.XSD_ATTRIBUTE__NAME))
            .andReturn(nameAttribute);

    Node excludeNode = EasyMock.createMock(Node.class);
    EasyMock.expect(excludeNode.getNodeType()).andReturn(Node.ELEMENT_NODE);
    EasyMock.expect(excludeNode.getLocalName()).andReturn("exclude");
    EasyMock.expect(excludeNode.getAttributes()).andReturn(excludeAttributes);

    NodeList childNodes = EasyMock.createMock(NodeList.class);
    EasyMock.expect(childNodes.getLength()).andReturn(1);
    EasyMock.expect(childNodes.item(0)).andReturn(excludeNode);

    Element evictExpired = EasyMock.createMock(Element.class);
    EasyMock.expect(evictExpired.getChildNodes()).andReturn(childNodes);
    EasyMock.replay(nameAttribute, excludeAttributes, excludeNode, childNodes, evictExpired);

    EhCacheConfigBeanDefinitionParser parser = new EhCacheConfigBeanDefinitionParser();
    List<CacheNameMatcher> matchers = parser.parseEvictExpiredElement(evictExpired);
    Assert.assertNotNull(matchers);
    Assert.assertEquals(2, matchers.size());
    Assert.assertEquals(EhCacheConfigBeanDefinitionParser.INCLUDE_ALL_CACHE_NAME_MATCHER, matchers.get(0));

    CacheNameMatcher matcher = matchers.get(1);
    Assert.assertTrue(matcher instanceof NotCacheNameMatcherImpl);
    NotCacheNameMatcherImpl casted = (NotCacheNameMatcherImpl) matcher;
    ExactCacheNameMatcherImpl wrapped = (ExactCacheNameMatcherImpl) casted.getWrapped();
    Assert.assertEquals("foo", wrapped.getName());

    EasyMock.verify(nameAttribute, excludeAttributes, excludeNode, childNodes, evictExpired);
}

From source file:com.surevine.alfresco.webscript.gsa.canuserseeitems.CanUserSeeItemsCommandWebscriptImpl.java

public Map<Integer, Object> requestToNodeRefCollection(String requestXMLString)
        throws SAXException, ParserConfigurationException, IOException, GSAInvalidParameterException {
    Map<Integer, Object> responseItems = new HashMap<Integer, Object>();

    Collection<NodeRef> nodeRefs = new ArrayList<NodeRef>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);//  www . ja  va  2  s .  com
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.parse(new ByteArrayInputStream(requestXMLString.getBytes("UTF-8")));

    NodeList allNodeRefs = document.getElementsByTagName("nodeRef");
    Element documentElement = document.getDocumentElement();
    String runAsUser = documentElement.getAttribute("runAsUser");

    //If the runAsUser is specified but doesn't exist, throw an error
    if (runAsUser != null && (!runAsUser.equals("")) && !personService.personExists(runAsUser)) {
        throw new GSAInvalidParameterException("The specified runAsUser(" + runAsUser + ") does not exist",
                null, 140611);
    }
    responseItems.put(RUN_AS_USER_KEY, runAsUser);

    int nodeRefCount = allNodeRefs.getLength();
    for (int i = 0; i < nodeRefCount; i++) {
        Node node = allNodeRefs.item(i);
        String nodeReference = node.getTextContent();

        NodeRef newNode = null;
        try {
            newNode = new NodeRef(nodeReference);
            if (_logger.isDebugEnabled()) {
                _logger.debug("Created nodeRef " + newNode + " from request");
            }
        } catch (Exception e) {
            //some problem creating the NodeRef - probably a syntactically invalid node ref.
            //ignore and continue:
            GSAProcessingException wrapped = new GSAProcessingException(
                    "Could not serialise " + nodeReference + " to a NodeRef Collection", e, 34831);
            _logger.warn(
                    "NodeRef could not be instantiated for supplied node reference [" + nodeReference + "].",
                    wrapped);
            continue;
        }

        nodeRefs.add(newNode);
    }

    responseItems.put(NODE_REFS_KEY, nodeRefs);

    return responseItems;
}