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:Main.java

private static void convert(Node toCopy, Node saveTo, Document doc) {
    Node newNode;/*from ww  w  .  j  av a 2  s . c  o m*/
    switch (toCopy.getNodeType()) {
    case Node.ELEMENT_NODE:
        Element newElement = doc.createElementNS(toCopy.getNamespaceURI(), toCopy.getNodeName());
        newNode = newElement;
        Element baseElement = (Element) toCopy;
        NamedNodeMap children = baseElement.getAttributes();
        for (int i = 0; i < children.getLength(); i++) {
            convertAttribute((Attr) children.item(i), newElement, doc);
        }
        break;
    case Node.TEXT_NODE:
        newNode = doc.createTextNode(toCopy.getTextContent());
        break;
    default:
        newNode = null;
    }
    if (newNode != null) {
        NodeList children = toCopy.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            convert(children.item(i), newNode, doc);
        }

        saveTo.appendChild(newNode);
    }
}

From source file:com.gargoylesoftware.htmlunit.html.impl.SimpleRange.java

private static String getText(final Node node) {
    if (node instanceof SelectableTextInput) {
        return ((SelectableTextInput) node).getText();
    }/*from www.j  av  a  2  s  . c  o m*/
    return node.getTextContent();
}

From source file:com.hp.mqm.atrf.core.configuration.FetchConfiguration.java

private static void parseNodes(Node node, String prefix, FetchConfiguration configuration) {
    NodeList nList = node.getChildNodes();
    for (int i = 0; i < nList.getLength(); i++) {
        Node nNode = nList.item(i);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            parseNodes(nNode, prefix + "." + nNode.getNodeName(), configuration);
        } else if (nNode.getNodeType() == Node.TEXT_NODE) {
            String value = nNode.getTextContent().trim();
            if (StringUtils.isNotEmpty(value)) {
                configuration.setProperty(prefix, value);
            }// ww w .ja  va2  s.  co m

        }
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

private static void readContentTypesConfiguration(Document xmlConfiguration, XPath xpath)
        throws XPathExpressionException {
    csvContentTypes = new HashSet<String>();
    shapeContentTypes = new HashSet<String>();
    compressedContentTypes = new HashSet<String>();

    // CSV/*from  ww  w. j a  v a 2s . c  om*/
    NodeList csvContentTypeNodes = (NodeList) xpath.compile("/configuration/files[@type='csv']/content-type")
            .evaluate(xmlConfiguration, XPathConstants.NODESET);
    for (int i = 0; i < csvContentTypeNodes.getLength(); i++) {
        Node csvContentTypeNode = csvContentTypeNodes.item(i);
        String csvContentType = csvContentTypeNode.getTextContent().toLowerCase();
        csvContentTypes.add(csvContentType);
    }

    // SHAPE
    NodeList shapeContentTypeNodes = (NodeList) xpath
            .compile("/configuration/files[@type='shape']/content-type")
            .evaluate(xmlConfiguration, XPathConstants.NODESET);
    for (int i = 0; i < shapeContentTypeNodes.getLength(); i++) {
        Node shapeContentTypeNode = shapeContentTypeNodes.item(i);
        String shapeContentType = shapeContentTypeNode.getTextContent().toLowerCase();
        shapeContentTypes.add(shapeContentType);
    }

    // COMPRESSED
    NodeList compressedContentTypeNodes = (NodeList) xpath
            .compile("/configuration/files[@type='compressed']/content-type")
            .evaluate(xmlConfiguration, XPathConstants.NODESET);
    for (int i = 0; i < compressedContentTypeNodes.getLength(); i++) {
        Node compressedContentTypeNode = compressedContentTypeNodes.item(i);
        String compressedContentType = compressedContentTypeNode.getTextContent().toLowerCase();
        compressedContentTypes.add(compressedContentType);
    }
}

From source file:edu.stanford.epad.epadws.queries.XNATQueries.java

public static String getXNATSubjectFieldValue(String sessionID, String xnatSubjectID, String fieldName) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    int xnatStatusCode;
    //log.info("Calling XNAT Subject info:" + XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID);

    try {/*from  www.  j a va  2 s  . com*/
        xnatStatusCode = client.executeMethod(method);
        String xmlResp = method.getResponseBodyAsString(10000);
        log.debug(xmlResp);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream is = new StringBufferInputStream(xmlResp);
        Document doc = db.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nodes = doc.getElementsByTagName("xnat:field");
        String value = "";
        String subjfieldname = "";
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            value = node.getTextContent();
            if (value != null)
                value = value.replace('\n', ' ').trim();
            NamedNodeMap attrs = node.getAttributes();
            String attrName = null;
            for (int j = 0; attrs != null && j < attrs.getLength(); j++) {
                attrName = attrs.item(j).getNodeName();
                subjfieldname = attrs.item(j).getNodeValue();
                if (fieldName.equalsIgnoreCase(subjfieldname))
                    return value;
            }
        }
        return value;
    } catch (Exception e) {
        log.warning(
                "Warning: error performing XNAT subject query " + XNATQueryUtil.buildSubjectURL(xnatSubjectID),
                e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateEclipseCsMetaXmlFileRule(String pkg, Class<?> module, Set<Node> children)
        throws Exception {
    final String moduleName = module.getSimpleName();
    final Set<String> properties = getFinalProperties(module);
    final Set<Field> fieldMessages = CheckUtil.getCheckMessages(module);
    final Set<String> messages = new TreeSet<>();

    for (Field fieldMessage : fieldMessages) {
        // below is required for package/private classes
        if (!fieldMessage.isAccessible()) {
            fieldMessage.setAccessible(true);
        }/* w  w w  .  j av a 2s. c o  m*/

        messages.add(fieldMessage.get(null).toString());
    }

    for (Node child : children) {
        final NamedNodeMap attributes = child.getAttributes();

        switch (child.getNodeName()) {
        case "alternative-name":
            final Node internalNameNode = attributes.getNamedItem("internal-name");

            Assert.assertNotNull(
                    pkg + " checkstyle-metadata.xml must contain an internal name for " + moduleName,
                    internalNameNode);

            final String internalName = internalNameNode.getTextContent();

            Assert.assertEquals(
                    pkg + " checkstyle-metadata.xml requires a valid internal-name for " + moduleName,
                    module.getName(), internalName);
            break;
        case "description":
            Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid description for " + moduleName,
                    "%" + moduleName + ".desc", child.getTextContent());
            break;
        case "property-metadata":
            final String propertyName = attributes.getNamedItem("name").getTextContent();

            Assert.assertTrue(pkg + " checkstyle-metadata.xml has an unknown parameter for " + moduleName + ": "
                    + propertyName, properties.remove(propertyName));

            final Node firstChild = child.getFirstChild().getNextSibling();

            Assert.assertNotNull(pkg + " checkstyle-metadata.xml requires atleast one child for " + moduleName
                    + ", " + propertyName, firstChild);
            Assert.assertEquals(pkg + " checkstyle-metadata.xml should have a description for the "
                    + "first child of " + moduleName + ", " + propertyName, "description",
                    firstChild.getNodeName());
            Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid description for " + moduleName
                    + ", " + propertyName, "%" + moduleName + "." + propertyName, firstChild.getTextContent());
            break;
        case "message-key":
            final String key = attributes.getNamedItem("key").getTextContent();

            Assert.assertTrue(
                    pkg + " checkstyle-metadata.xml has an unknown message for " + moduleName + ": " + key,
                    messages.remove(key));
            break;
        default:
            Assert.fail(pkg + " checkstyle-metadata.xml unknown node for " + moduleName + ": "
                    + child.getNodeName());
            break;
        }
    }

    for (String property : properties) {
        Assert.fail(pkg + " checkstyle-metadata.xml missing parameter for " + moduleName + ": " + property);
    }

    for (String message : messages) {
        Assert.fail(pkg + " checkstyle-metadata.xml missing message for " + moduleName + ": " + message);
    }
}

From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java

public static SuggestUpdateConfig getUpdateHandlerConfig(final SolrConfig config) {
    final SuggestUpdateConfig suggestUpdateConfig = new SuggestUpdateConfig();

    final Node solrServerNode = config.getNode("updateHandler/suggest/solrServer", false);
    if (solrServerNode != null) {
        try {//  ww  w  .  j  av a 2 s.co  m
            final Node classNode = solrServerNode.getAttributes().getNamedItem("class");
            String className;
            if (classNode != null) {
                className = classNode.getTextContent();
            } else {
                className = "org.codelibs.solr.lib.server.SolrLibHttpSolrServer";
            }
            @SuppressWarnings("unchecked")
            final Class<? extends SolrServer> clazz = (Class<? extends SolrServer>) Class.forName(className);
            final String arg = config.getVal("updateHandler/suggest/solrServer/arg", false);
            SolrServer solrServer;
            if (StringUtils.isNotBlank(arg)) {
                final Constructor<? extends SolrServer> constructor = clazz.getConstructor(String.class);
                solrServer = constructor.newInstance(arg);
            } else {
                solrServer = clazz.newInstance();
            }

            final String username = config.getVal("updateHandler/suggest/solrServer/credentials/username",
                    false);
            final String password = config.getVal("updateHandler/suggest/solrServer/credentials/password",
                    false);
            if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)
                    && solrServer instanceof SolrLibHttpSolrServer) {
                final SolrLibHttpSolrServer solrLibHttpSolrServer = (SolrLibHttpSolrServer) solrServer;
                final URL u = new URL(arg);
                final AuthScope authScope = new AuthScope(u.getHost(), u.getPort());
                final Credentials credentials = new UsernamePasswordCredentials(username, password);
                solrLibHttpSolrServer.setCredentials(authScope, credentials);
                solrLibHttpSolrServer.addRequestInterceptor(new PreemptiveAuthInterceptor());
            }

            final NodeList childNodes = solrServerNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                final Node node = childNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    final String name = node.getNodeName();
                    if (!"arg".equals(name) && !"credentials".equals(name)) {
                        final String value = node.getTextContent();
                        final Node typeNode = node.getAttributes().getNamedItem("type");
                        final Method method = clazz.getMethod(
                                "set" + name.substring(0, 1).toUpperCase() + name.substring(1),
                                getMethodArgClass(typeNode));
                        method.invoke(solrServer, getMethodArgValue(typeNode, value));
                    }
                }
            }
            if (solrServer instanceof SolrLibHttpSolrServer) {
                ((SolrLibHttpSolrServer) solrServer).init();
            }
            suggestUpdateConfig.setSolrServer(solrServer);
        } catch (final Exception e) {
            throw new FessSuggestException("Failed to load SolrServer.", e);
        }
    }

    final String labelFields = config.getVal("updateHandler/suggest/labelFields", false);
    if (StringUtils.isNotBlank(labelFields)) {
        suggestUpdateConfig.setLabelFields(labelFields.trim().split(","));
    }
    final String roleFields = config.getVal("updateHandler/suggest/roleFields", false);
    if (StringUtils.isNotBlank(roleFields)) {
        suggestUpdateConfig.setRoleFields(roleFields.trim().split(","));
    }

    final String expiresField = config.getVal("updateHandler/suggest/expiresField", false);
    if (StringUtils.isNotBlank(expiresField)) {
        suggestUpdateConfig.setExpiresField(expiresField);
    }
    final String segmentField = config.getVal("updateHandler/suggest/segmentField", false);
    if (StringUtils.isNotBlank(segmentField)) {
        suggestUpdateConfig.setSegmentField(segmentField);
    }
    final String updateInterval = config.getVal("updateHandler/suggest/updateInterval", false);
    if (StringUtils.isNotBlank(updateInterval) && StringUtils.isNumeric(updateInterval)) {
        suggestUpdateConfig.setUpdateInterval(Long.parseLong(updateInterval));
    }

    //set suggestFieldInfo
    final NodeList nodeList = config.getNodeList("updateHandler/suggest/suggestFieldInfo", true);
    for (int i = 0; i < nodeList.getLength(); i++) {
        try {
            final SuggestUpdateConfig.FieldConfig fieldConfig = new SuggestUpdateConfig.FieldConfig();
            final Node fieldInfoNode = nodeList.item(i);
            final NamedNodeMap fieldInfoAttributes = fieldInfoNode.getAttributes();
            final Node fieldNameNode = fieldInfoAttributes.getNamedItem("fieldName");
            final String fieldName = fieldNameNode.getNodeValue();
            if (StringUtils.isBlank(fieldName)) {
                continue;
            }
            fieldConfig.setTargetFields(fieldName.trim().split(","));
            if (logger.isInfoEnabled()) {
                for (final String s : fieldConfig.getTargetFields()) {
                    logger.info("fieldName : " + s);
                }
            }

            final NodeList fieldInfoChilds = fieldInfoNode.getChildNodes();
            for (int j = 0; j < fieldInfoChilds.getLength(); j++) {
                final Node fieldInfoChildNode = fieldInfoChilds.item(j);
                final String fieldInfoChildNodeName = fieldInfoChildNode.getNodeName();

                if ("tokenizerFactory".equals(fieldInfoChildNodeName)) {
                    //field tokenier settings
                    final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = new SuggestUpdateConfig.TokenizerConfig();

                    final NamedNodeMap tokenizerFactoryAttributes = fieldInfoChildNode.getAttributes();
                    final Node tokenizerClassNameNode = tokenizerFactoryAttributes.getNamedItem("class");
                    final String tokenizerClassName = tokenizerClassNameNode.getNodeValue();
                    tokenizerConfig.setClassName(tokenizerClassName);
                    if (logger.isInfoEnabled()) {
                        logger.info("tokenizerFactory : " + tokenizerClassName);
                    }

                    final Map<String, String> args = new HashMap<String, String>();
                    for (int k = 0; k < tokenizerFactoryAttributes.getLength(); k++) {
                        final Node attribute = tokenizerFactoryAttributes.item(k);
                        final String key = attribute.getNodeName();
                        final String value = attribute.getNodeValue();
                        if (!"class".equals(key)) {
                            args.put(key, value);
                        }
                    }
                    if (!args.containsKey(USER_DICT_PATH)) {
                        final String userDictPath = System.getProperty(SuggestConstants.USER_DICT_PATH, "");
                        if (StringUtils.isNotBlank(userDictPath)) {
                            args.put(USER_DICT_PATH, userDictPath);
                        }
                        final String userDictEncoding = System.getProperty(SuggestConstants.USER_DICT_ENCODING,
                                "");
                        if (StringUtils.isNotBlank(userDictEncoding)) {
                            args.put(USER_DICT_ENCODING, userDictEncoding);
                        }
                    }
                    tokenizerConfig.setArgs(args);

                    fieldConfig.setTokenizerConfig(tokenizerConfig);
                } else if ("suggestReadingConverter".equals(fieldInfoChildNodeName)) {
                    //field reading converter settings
                    final NodeList converterNodeList = fieldInfoChildNode.getChildNodes();
                    for (int k = 0; k < converterNodeList.getLength(); k++) {
                        final SuggestUpdateConfig.ConverterConfig converterConfig = new SuggestUpdateConfig.ConverterConfig();

                        final Node converterNode = converterNodeList.item(k);
                        if (!"converter".equals(converterNode.getNodeName())) {
                            continue;
                        }

                        final NamedNodeMap converterAttributes = converterNode.getAttributes();
                        final Node classNameNode = converterAttributes.getNamedItem("class");
                        final String className = classNameNode.getNodeValue();
                        converterConfig.setClassName(className);
                        if (logger.isInfoEnabled()) {
                            logger.info("converter : " + className);
                        }

                        final Map<String, String> properties = new HashMap<String, String>();
                        for (int l = 0; l < converterAttributes.getLength(); l++) {
                            final Node attribute = converterAttributes.item(l);
                            final String key = attribute.getNodeName();
                            final String value = attribute.getNodeValue();
                            if (!"class".equals(key)) {
                                properties.put(key, value);
                            }
                        }
                        converterConfig.setProperties(properties);
                        if (logger.isInfoEnabled()) {
                            logger.info("converter properties = " + properties);
                        }
                        fieldConfig.addConverterConfig(converterConfig);
                    }
                } else if ("suggestNormalizer".equals(fieldInfoChildNodeName)) {
                    //field normalizer settings
                    final NodeList normalizerNodeList = fieldInfoChildNode.getChildNodes();
                    for (int k = 0; k < normalizerNodeList.getLength(); k++) {
                        final SuggestUpdateConfig.NormalizerConfig normalizerConfig = new SuggestUpdateConfig.NormalizerConfig();

                        final Node normalizerNode = normalizerNodeList.item(k);
                        if (!"normalizer".equals(normalizerNode.getNodeName())) {
                            continue;
                        }

                        final NamedNodeMap normalizerAttributes = normalizerNode.getAttributes();
                        final Node classNameNode = normalizerAttributes.getNamedItem("class");
                        final String className = classNameNode.getNodeValue();
                        normalizerConfig.setClassName(className);
                        if (logger.isInfoEnabled()) {
                            logger.info("normalizer : " + className);
                        }

                        final Map<String, String> properties = new HashMap<String, String>();
                        for (int l = 0; l < normalizerAttributes.getLength(); l++) {
                            final Node attribute = normalizerAttributes.item(l);
                            final String key = attribute.getNodeName();
                            final String value = attribute.getNodeValue();
                            if (!"class".equals(key)) {
                                properties.put(key, value);
                            }
                        }
                        normalizerConfig.setProperties(properties);
                        if (logger.isInfoEnabled()) {
                            logger.info("normalize properties = " + properties);
                        }
                        fieldConfig.addNormalizerConfig(normalizerConfig);
                    }
                }
            }

            suggestUpdateConfig.addFieldConfig(fieldConfig);
        } catch (final Exception e) {
            throw new FessSuggestException("Failed to load Suggest Field Info.", e);
        }
    }

    return suggestUpdateConfig;
}

From source file:org.dasein.cloud.terremark.Terremark.java

public static String getTaskHref(Document doc, String taskName) {
    String href = null;/*from   w w  w .j  a va 2  s.com*/
    NodeList taskElements = doc.getElementsByTagName(Terremark.TASK_TAG);
    for (int i = 0; i < taskElements.getLength(); i++) {
        Node taskElement = taskElements.item(i);
        NodeList taskChildren = taskElement.getChildNodes();
        for (int j = 0; j < taskChildren.getLength(); j++) {
            Node taskChild = taskChildren.item(j);
            if (taskChild.getNodeName().equals(Terremark.OPERATION_TAG)) {
                if (taskChild.getTextContent().equals(taskName)) {
                    href = taskElement.getAttributes().getNamedItem(Terremark.HREF).getNodeValue();
                    break;
                }
            }
        }
        if (href != null) {
            break;
        }
    }
    return href;
}

From source file:fr.afcepf.atod.wine.data.parser.XmlParser.java

private static ProductVintage getWineVintage(Node VintageNode) {
    String vintage = VintageNode.getTextContent();
    ProductVintage oVintage = null;//from ww w  .j a va 2s.  com
    try {
        if (vintage != null) {
            if (vintages.containsKey(vintage) == false) {
                oVintage = new ProductVintage(null, Integer.parseInt(vintage));
                vintages.put(vintage, oVintage);
            } else {
                oVintage = (ProductVintage) vintages.get(vintage);
            }
        }
    } catch (NumberFormatException e) {
        //
    }
    return oVintage;
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.QueryTests.java

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription, find and add the simpleQuery service url
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));
        Node simpleQueryUrl = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:simpleQuery/oslc_cm:url", baseDoc,
                XPathConstants.NODE);
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { simpleQueryUrl.getTextContent() });
        return data;
    }/*from www .j  a  va 2  s. c o  m*/

    String respBody = EntityUtils.toString(resp.getEntity());
    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(respBody);

    //ArrayList to contain the urls from all of the SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        String serviceUrl = OSLCUtils.absoluteUrlFromRelative(base, sDescs.item(i).getNodeValue());
        Collection<Object[]> subCollection = getReferencedUrls(serviceUrl);
        Iterator<Object[]> iter = subCollection.iterator();
        while (iter.hasNext()) {
            data.add(iter.next());
        }
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //simple query services from the eventual service description documents from them as well.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        String uri = spcs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        if (!uri.equals(base)) {
            Collection<Object[]> subCollection = getReferencedUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}