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:org.escidoc.browser.elabsmodul.service.ELabsService.java

private static InvestigationBean resolveInvestigation(final ContainerProxy containerProxy) {
    final String URI_DC = "http://purl.org/dc/elements/1.1/";
    final String URI_EL = "http://escidoc.org/ontologies/bw-elabs/re#";
    final String URI_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

    if (containerProxy == null) {
        throw new NullPointerException("Container Proxy is null.");
    }//from  w  w  w .j  a va  2  s  .c  o  m
    final InvestigationBean investigationBean = new InvestigationBean();
    final Element e = containerProxy.getMetadataRecords().get("escidoc").getContent();
    investigationBean.setObjid(containerProxy.getId());

    if (!(("Investigation".equals(e.getLocalName()) && URI_EL.equals(e.getNamespaceURI()))
            || "el:Investigation".equals(e.getTagName()))) {
        LOG.error("Container is not an eLabs Investigation");
        return investigationBean;
    }

    final NodeList nodeList = e.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        final String nodeName = node.getLocalName();
        final String nsUri = node.getNamespaceURI();

        if (nodeName == null || nsUri == null) {
            continue;
        }

        if ("title".equals(nodeName) && URI_DC.equals(nsUri)) {
            investigationBean.setName(node.getTextContent());
        } else if ("description".equals(nodeName) && URI_DC.equals(nsUri)) {
            investigationBean.setDescription(node.getTextContent());
        } else if ("max-runtime".equals(nodeName) && URI_EL.equals(nsUri)) {
            investigationBean.setMaxRuntime("<<not used>>");
            try {
                investigationBean.setMaxRuntimeInMin(Integer.valueOf(node.getTextContent()));
            } catch (final NumberFormatException nfe) {
                LOG.error(nfe.getMessage());
                investigationBean.setMaxRuntimeInMin(0);
            }
        } else if ("deposit-endpoint".equals(nodeName) && URI_EL.equals(nsUri)) {
            investigationBean.setDepositEndpoint(node.getTextContent());
        } else if ("investigator".equals(nodeName) && URI_EL.equals(nsUri)) {
            final String investigatorId = node.getAttributes().getNamedItemNS(URI_RDF, "resource")
                    .getTextContent();
            investigationBean.setInvestigator(investigatorId);
        } else if ("rig".equals(nodeName) && URI_EL.equals(nsUri)) {
            final String rigId = node.getAttributes().getNamedItemNS(URI_RDF, "resource").getTextContent();
            if (StringUtils.notEmpty(rigId)) {
                final RigBean rigBean = new RigBean();
                rigBean.setObjectId(rigId);
                investigationBean.setRigBean(rigBean);
            }
        } else if ("instrument".equals(nodeName) && URI_EL.equals(nsUri)) {
            final String instrument = node.getAttributes().getNamedItemNS(URI_RDF, "resource").getTextContent();
            final String folder = node.getTextContent().trim();
            investigationBean.getInstrumentFolder().put(instrument, folder);
        }
    }
    return investigationBean;
}

From source file:com.amalto.webapp.core.util.Util.java

public static String getDefaultLanguage() throws Exception {
    String defaultLanguage = ""; //$NON-NLS-1$
    String userName = LocalUser.getLocalUser().getUsername();
    WSItemPK itemPK = new WSItemPK(new WSDataClusterPK(DATACLUSTER_PK), PROVISIONING_CONCEPT,
            new String[] { userName });
    if (userName != null && userName.length() > 0) {
        Document doc = XMLUtils.parse(Util.getPort().getItem(new WSGetItem(itemPK)).getContent());
        if (doc.getElementsByTagName("language") != null) { //$NON-NLS-1$
            Node language = doc.getElementsByTagName("language").item(0); //$NON-NLS-1$
            if (language != null) {
                return language.getTextContent();
            }/*from  w w w .j a va2  s  .co m*/
        }
    }
    return defaultLanguage;
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Obtain the STIX version from the Content_Binding urn
 *
 * @param node Content_Binding node/*from w w  w .j a  va 2s. c  o  m*/
 * @return a String containing the STIX version
 * @throws DOMException DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation
 * is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
 * <a href="https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/DOMException.html">Reference to Oracle Documentation.</a>
 *
 */
private static String getStixVersion(Node node) throws DOMException {
    try {
        String urnStr = "";
        if (node.hasAttributes()) {
            Attr attr = (Attr) node.getAttributes().getNamedItem("binding_id");
            if (attr != null) {
                urnStr = attr.getValue();
            }
        }
        if (urnStr.isEmpty()) {
            urnStr = node.getTextContent();
        }
        if (urnStr != null && !urnStr.isEmpty()) {
            int lastIndex = urnStr.lastIndexOf(":");
            String version = "";
            if (lastIndex >= 0) {
                version = urnStr.substring(lastIndex + 1);
            }
            return version;
        }
    } catch (DOMException e) {
        logger.debug("DOMException when attempting to parse binding id from a STIX node. ");
        throw e;
    }
    return "";
}

From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java

private static void validateUsageExample(String fileName, String sectionName, Node subSection) {
    final String text = subSection.getTextContent().replace("Checkstyle Style", "").replace("Google Style", "")
            .replace("Sun Style", "").trim();

    Assert.assertTrue(/*from  w  w  w.j  a  v a  2s .c  o m*/
            fileName + " section '" + sectionName + "' has unknown text in 'Example of Usage': " + text,
            text.isEmpty());

    boolean hasCheckstyle = false;
    boolean hasGoogle = false;
    boolean hasSun = false;

    for (Node node : XmlUtil.findChildElementsByTag(subSection, "a")) {
        final String url = node.getAttributes().getNamedItem("href").getTextContent();
        final String linkText = node.getTextContent().trim();
        String expectedUrl = null;

        if ("Checkstyle Style".equals(linkText)) {
            hasCheckstyle = true;
            expectedUrl = "https://github.com/search?q=" + "path%3Aconfig+filename%3Acheckstyle_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;
        } else if ("Google Style".equals(linkText)) {
            hasGoogle = true;
            expectedUrl = "https://github.com/search?q="
                    + "path%3Asrc%2Fmain%2Fresources+filename%3Agoogle_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;

            Assert.assertTrue(
                    fileName + " section '" + sectionName
                            + "' should be in google_checks.xml or not reference 'Google Style'",
                    GOOGLE_MODULES.contains(sectionName));
        } else if ("Sun Style".equals(linkText)) {
            hasSun = true;
            expectedUrl = "https://github.com/search?q="
                    + "path%3Asrc%2Fmain%2Fresources+filename%3Asun_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;

            Assert.assertTrue(
                    fileName + " section '" + sectionName
                            + "' should be in sun_checks.xml or not reference 'Sun Style'",
                    SUN_MODULES.contains(sectionName));
        }

        Assert.assertEquals(fileName + " section '" + sectionName + "' should have matching url", expectedUrl,
                url);
    }

    Assert.assertTrue(fileName + " section '" + sectionName + "' should have a checkstyle section",
            hasCheckstyle);
    Assert.assertTrue(
            fileName + " section '" + sectionName + "' should have a google section since it is in it's config",
            hasGoogle || !GOOGLE_MODULES.contains(sectionName));
    Assert.assertTrue(
            fileName + " section '" + sectionName + "' should have a sun section since it is in it's config",
            hasSun || !SUN_MODULES.contains(sectionName));
}

From source file:lv.semti.Thesaurus.struct.Gloss.java

public Gloss(Node dNode) {
    text = dNode.getTextContent();
}

From source file:Main.java

public static String elementToString(Node n) {

    String name = n.getNodeName();

    short type = n.getNodeType();

    if (Node.CDATA_SECTION_NODE == type) {
        return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
    }//from ww  w. j a  v a  2s. c  o m

    if (name.startsWith("#")) {
        return "";
    }

    StringBuilder sb = new StringBuilder();
    sb.append('<').append(name);

    NamedNodeMap attrs = n.getAttributes();
    if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\"");
        }
    }

    String textContent = null;
    NodeList children = n.getChildNodes();

    if (children.getLength() == 0) {
        //      if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) {
        if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) {
            sb.append(textContent).append("</").append(name).append('>');

        } else {
            sb.append("/>");
        }
    } else {
        sb.append('>');
        boolean hasValidChildren = false;
        for (int i = 0; i < children.getLength(); i++) {
            String childToString = elementToString(children.item(i));
            if (!"".equals(childToString)) {
                sb.append('\n').append(childToString);
                hasValidChildren = true;
            }
        }
        if (hasValidChildren) {
            sb.append('\n');
        }

        //      if (!hasValidChildren && ((textContent = XMLUtil.getTextContent(n)) != null)) {
        if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) {
            sb.append(textContent);
        }

        sb.append("</").append(name).append('>');
    }

    return sb.toString();
}

From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java

private static void validateStyleModules(Set<Node> checks, Set<Node> configs, Set<String> styleChecks,
        String fileName, String ruleName) {
    final Iterator<Node> itrChecks = checks.iterator();
    final Iterator<Node> itrConfigs = configs.iterator();

    while (itrChecks.hasNext()) {
        final Node module = itrChecks.next();
        final String moduleName = module.getTextContent().trim();

        if (!module.getAttributes().getNamedItem("href").getTextContent().startsWith("config_")) {
            continue;
        }//w  ww. j  a  v  a2s  .co m

        Assert.assertTrue(
                fileName + " rule '" + ruleName + "' module '" + moduleName + "' shouldn't end with 'Check'",
                !moduleName.endsWith("Check"));

        styleChecks.remove(moduleName);

        for (String configName : new String[] { "config", "test" }) {
            Node config = null;

            try {
                config = itrConfigs.next();
            } catch (NoSuchElementException ignore) {
                Assert.fail(fileName + " rule '" + ruleName + "' module '" + moduleName
                        + "' is missing the config link: " + configName);
            }

            Assert.assertEquals(fileName + " rule '" + ruleName + "' module '" + moduleName
                    + "' has mismatched config/test links", configName, config.getTextContent().trim());

            final String configUrl = config.getAttributes().getNamedItem("href").getTextContent();

            if ("config".equals(configName)) {
                final String expectedUrl = "https://github.com/search?q="
                        + "path%3Asrc%2Fmain%2Fresources+filename%3Agoogle_checks.xml+"
                        + "repo%3Acheckstyle%2Fcheckstyle+" + moduleName;

                Assert.assertEquals(fileName + " rule '" + ruleName + "' module '" + moduleName
                        + "' should have matching " + configName + " url", expectedUrl, configUrl);
            } else if ("test".equals(configName)) {
                Assert.assertTrue(
                        fileName + " rule '" + ruleName + "' module '" + moduleName + "' should have matching "
                                + configName + " url",
                        configUrl.startsWith("https://github.com/checkstyle/checkstyle/"
                                + "blob/master/src/it/java/com/google/checkstyle/test/"));
                Assert.assertTrue(fileName + " rule '" + ruleName + "' module '" + moduleName
                        + "' should have matching " + configName + " url",
                        configUrl.endsWith("/" + moduleName + "Test.java"));

                Assert.assertTrue(
                        fileName + " rule '" + ruleName + "' module '" + moduleName
                                + "' should have a test that exists",
                        new File(configUrl.substring(53).replace('/', File.separatorChar)).exists());
            }
        }
    }

    Assert.assertFalse(fileName + " rule '" + ruleName + "' has too many configs", itrConfigs.hasNext());
}

From source file:mekhq.campaign.finances.Finances.java

public static Finances generateInstanceFromXML(Node wn) {
    Finances retVal = new Finances();
    NodeList nl = wn.getChildNodes();
    for (int x = 0; x < nl.getLength(); x++) {
        Node wn2 = nl.item(x);
        if (wn2.getNodeName().equalsIgnoreCase("transaction")) {
            retVal.transactions.add(Transaction.generateInstanceFromXML(wn2));
        } else if (wn2.getNodeName().equalsIgnoreCase("loan")) {
            retVal.loans.add(Loan.generateInstanceFromXML(wn2));
        } else if (wn2.getNodeName().equalsIgnoreCase("asset")) {
            retVal.assets.add(Asset.generateInstanceFromXML(wn2));
        } else if (wn2.getNodeName().equalsIgnoreCase("loanDefaults")) {
            retVal.loanDefaults = Integer.parseInt(wn2.getTextContent().trim());
        } else if (wn2.getNodeName().equalsIgnoreCase("wentIntoDebt")) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            try {
                retVal.wentIntoDebt = df.parse(wn2.getTextContent().trim());
            } catch (DOMException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();/* www .  j a v a  2 s  . c  o m*/
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return retVal;
}

From source file:lv.semti.Thesaurus.struct.Lemma.java

public Lemma(Node vfNode) {
    text = vfNode.getTextContent();
    pronunciation = ((org.w3c.dom.Element) vfNode).getAttribute("ru");
    if ("".equals(pronunciation))
        pronunciation = null;/*w  ww .  j  a  va 2s  .  c  o  m*/
    if (pronunciation == null)
        return;
    if (pronunciation.startsWith("["))
        pronunciation = pronunciation.substring(1);
    if (pronunciation.endsWith("]"))
        pronunciation = pronunciation.substring(0, pronunciation.length() - 1);
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

private static DiscoverDeviceType checkCompllent(String ipAddress, InfrastructureDevice device) {
    String compllentHtml = String.format("https://%s/SystemExplorer.asp", ipAddress);
    DiscoverDeviceType retVal = DiscoverDeviceType.UNKNOWN;
    CredentialEntity cred = getCredentialDAO().findById(device.getStorageCredentialId());
    try {/*from  w  w w  . j a v  a  2 s  .c  o m*/
        String compellentResponse = getHTML(compllentHtml);
        if (compellentResponse != null && compellentResponse.toUpperCase().contains("COMPELLENT")) {
            // Ok, we know this device is compellent, but we don't know if it's the master or a slave.
            // Make a compellent api call to get the IP of the master, then compare it to this IP.
            // if they don't match, this is a slave and we want to skip it.

            //                -bash-4.1# java -jar /etc/puppetlabs/puppet/modules/compellent/lib/puppet/files/CompCU-6.3.jar -host 172.17.10.41 -user Admin -password P@ssw0rd -c "system show" -xml xmlfilename
            //                <compellent>
            //                <system>
            //                <SerialNumber>24260</SerialNumber>
            //                <Name>SC8000-10-50</Name>
            //                <ManagementIP>172.17.10.40</ManagementIP>
            //                <Version>6.3.2.16</Version>
            //                <OperationMode>Normal</OperationMode>
            //                <PortsBalanced>No</PortsBalanced>
            //                <MailServer></MailServer>
            //                <BackupMailServer></BackupMailServer>
            //                </system>
            //                </compellent>

            // call compellent command line
            File devicesDir = new File(TEMP_PATH);
            File tempFile = File.createTempFile(ipAddress, ".tmp.conf", devicesDir);
            ExecuteSystemCommands cmdRunner = ExecuteSystemCommands.getInstance();

            String[] volumeCommand = { "java", "-jar",
                    "/etc/puppetlabs/puppet/modules/compellent/lib/puppet/files/CompCU.jar", "-host", ipAddress,
                    "-user", cred.getUsername(), "-password", cred.getPasswordData().getString(), "-c",
                    "system show -xml " + tempFile.getAbsolutePath() };

            //LOGGER.debug("Calling Compellent : " + volumeCommand);
            CommandResponse cmdresponse = cmdRunner.runCommandWithConsoleOutput(volumeCommand);
            LOGGER.debug("Return code: " + cmdresponse.getReturnCode() + " Return message: "
                    + cmdresponse.getReturnMessage());
            device.setDiscoveryResponse(cmdresponse.getReturnMessage());
            if (cmdresponse.getReturnCode().equalsIgnoreCase("0")) {
                // read the generated XML file, look for managementIP
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(tempFile);

                NodeList nList = doc.getElementsByTagName("ManagementIP");
                String reportedManagerIP = null;
                for (int temp = 0; temp < nList.getLength(); temp++) {

                    Node nNode = nList.item(temp);
                    reportedManagerIP = nNode.getTextContent();
                }

                // compare the management ip we found with the one we're discovering
                if (reportedManagerIP != null && reportedManagerIP.equals(ipAddress)) {
                    retVal = DiscoverDeviceType.COMPELLENT;
                } else {
                    LOGGER.info("Skipping compellent IP " + ipAddress + " because it is not the management IP, "
                            + reportedManagerIP);
                }
            }

            try {
                tempFile.delete();
            } catch (Exception e) {
                LOGGER.warn("could not delete temp file " + tempFile.getAbsolutePath() + ", ignoring.");
            }
        } else {
            LOGGER.debug("Check for Compellent didn't detect a known pattern in HTML response: "
                    + compellentResponse);
            device.setDiscoveryResponse(compellentResponse);
        }
    } catch (Exception ioe) {
        LOGGER.debug("In DeviceTypeCheck.checkCompllent, could not connect to " + ipAddress + " because of "
                + ioe.getMessage() + ".  Ignoring.");
    }

    return retVal;
}