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.liferay.ide.server.util.ServerUtil.java

public static String[] getServletFilterNames(IPath portalDir) throws Exception {
    List<String> retval = new ArrayList<String>();

    File filtersWebXmlFile = portalDir.append("WEB-INF/liferay-web.xml").toFile(); //$NON-NLS-1$

    if (!filtersWebXmlFile.exists()) {
        filtersWebXmlFile = portalDir.append("WEB-INF/web.xml").toFile(); //$NON-NLS-1$
    }/*from  ww  w  .  j a va  2 s  .c o  m*/

    if (filtersWebXmlFile.exists()) {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(filtersWebXmlFile);

        NodeList filterNameElements = document.getElementsByTagName("filter-name"); //$NON-NLS-1$

        for (int i = 0; i < filterNameElements.getLength(); i++) {
            Node filterNameElement = filterNameElements.item(i);

            String content = filterNameElement.getTextContent();

            if (!CoreUtil.isNullOrEmpty(content)) {
                retval.add(content.trim());
            }
        }
    }

    return retval.toArray(new String[0]);
}

From source file:com.evolveum.midpoint.prism.xml.XmlTypeConverter.java

private static <T> T tryConvertPrimitiveScalar(NodeList valueNodes, Class<T> type) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < valueNodes.getLength(); i++) {
        Node node = valueNodes.item(i);
        if (DOMUtil.isJunk(node)) {
            continue;
        }// www .j  a  v a  2s  .co  m
        if (node.getNodeType() == Node.TEXT_NODE) {
            sb.append(node.getTextContent());
        } else {
            // We have failed
            return null;
        }
    }
    if (type.equals(Object.class)) {
        // Try string as default type
        return (T) XmlTypeConverter.toJavaValue(sb.toString(), String.class);
    }
    return XmlTypeConverter.toJavaValue(sb.toString(), type);
}

From source file:de.matzefratze123.heavyspleef.util.I18NNew.java

private static void readEntry(Node node, String parentEntry) {
    NodeList list = node.getChildNodes();

    for (int i = 0; i < list.getLength(); i++) {
        Node childNode = list.item(i);
        String nodeName = childNode.getNodeName();

        if (nodeName.equalsIgnoreCase(MESSAGE_ENTRY)) {
            NamedNodeMap attributes = childNode.getAttributes();
            Node idNode = attributes.getNamedItem(ID_ATTRIBUTE);
            if (idNode == null) {
                Logger.warning("Warning: No id for message in " + MESSAGES_FILE + ". Ignoring message...");
                continue;
            }//ww w. j ava 2  s .c o  m

            String id = idNode.getNodeValue();
            String value = childNode.getTextContent();

            messages.put(parentEntry + id, value);
        } else if (nodeName.equalsIgnoreCase(ENTRY_ENTRY)) {
            NamedNodeMap attributes = childNode.getAttributes();
            Node nameNode = attributes.getNamedItem(ENTRY_NAME);
            String entryName = nameNode.getNodeValue();

            readEntry(childNode, parentEntry + entryName + ".");
        }
    }
}

From source file:eu.prestoprime.p4gui.connection.AccessConnection.java

public static List<Event> getEvents(P4Service service, String id) {
    final String PREMIS_NS = "http://www.loc.gov/standards/premis/v1";

    DIP dip = AccessConnection.getDIP(service, id);
    NodeList eventNodes = ((Document) dip.getContent()).getDocumentElement().getElementsByTagNameNS(PREMIS_NS,
            "event");
    logger.debug("Found " + eventNodes.getLength() + " PREMIS events...");

    List<Event> events = new ArrayList<>();
    for (int i = 0; i < eventNodes.getLength(); i++) {
        Node eventNode = eventNodes.item(i);
        do {//  w  ww.jav a  2s .  c om
            if (eventNode instanceof Element) {
                Node typeNode = ((Element) eventNode).getElementsByTagNameNS(PREMIS_NS, "eventType").item(0);
                Node dateTimeNode = ((Element) eventNode).getElementsByTagNameNS(PREMIS_NS, "eventDateTime")
                        .item(0);
                Node detailNode = ((Element) eventNode).getElementsByTagNameNS(PREMIS_NS, "eventDetail")
                        .item(0);

                String type = typeNode.getTextContent();
                Calendar dateTime;
                try {
                    dateTime = DatatypeFactory.newInstance()
                            .newXMLGregorianCalendar(dateTimeNode.getTextContent()).toGregorianCalendar();
                } catch (Exception e) {
                    dateTime = new GregorianCalendar();
                }
                String detail = detailNode.getTextContent();

                logger.debug("Found event " + type + "...");

                Event event = new Event(type, dateTime, detail);
                events.add(event);
            }
        } while ((eventNode = eventNode.getNextSibling()) != null);
    }
    return events;
}

From source file:com.photon.phresco.framework.commons.QualityUtil.java

public static void changeTestName(String performancePath, String testName) throws Exception {
    File buildPathXml = null;/*from  www .  j  a v  a 2  s.  c om*/
    S_LOGGER.debug("Entering Method QualityUtil.testSuite() performance path and TestName " + performancePath
            + " " + testName);
    buildPathXml = new File(performancePath + buildFileName);
    Document document = com.photon.phresco.framework.impl.util.FrameworkUtil.getDocument(buildPathXml);
    String fileNameNode = "project/target[@name='init']/property[@name='jmeter.result.file']";
    NodeList nodelist = org.apache.xpath.XPathAPI.selectNodeList(document, fileNameNode);
    if (nodelist != null && nodelist.getLength() > 0) {
        Node stringProp = nodelist.item(0);
        NamedNodeMap attributes = stringProp.getAttributes();
        Node valueAttr = attributes.getNamedItem("value");
        String valueAttrTxt = valueAttr.getTextContent();
        S_LOGGER.debug("Load test xml name "
                + valueAttrTxt.substring(0, valueAttrTxt.indexOf("/") + 1).concat(testName + ".xml"));
        valueAttr.setTextContent(
                valueAttrTxt.substring(0, valueAttrTxt.indexOf("/") + 1).concat(testName + ".xml"));
    }
    saveDocument(buildPathXml, document);
}

From source file:edu.stanford.muse.webapp.Accounts.java

/** does account setup and login (and look up default folder if well-known account) from the given request.
 * request params are loginName<N>, password<N>, etc (see loginForm for details).
 * returns an object with {status: 0} if success, or {status: <non-zero>, errorMessage: '... '} if failure.
 * if success and account has a well-known sent mail folder, the returned object also has something like: 
 * {defaultFolder: '[Gmail]/Sent Mail', defaultFolderCount: 1033}
 * accounts on the login page are numbered 0 upwards. */
public static JSONObject login(HttpServletRequest request, int accountNum) throws IOException, JSONException {
    JSONObject result = new JSONObject();

    HttpSession session = request.getSession();
    // allocate the fetcher if it doesn't already exist
    MuseEmailFetcher m = null;//from  ww w .  ja  v a2  s.co m
    synchronized (session) // synchronize, otherwise may lose the fetcher when multiple accounts are specified and are logged in to simult.
    {
        m = (MuseEmailFetcher) JSPHelper.getSessionAttribute(session, "museEmailFetcher");
        boolean doIncremental = request.getParameter("incremental") != null;

        if (m == null || !doIncremental) {
            m = new MuseEmailFetcher();
            session.setAttribute("museEmailFetcher", m);
        }
    }

    // note: the same params get posted with every accountNum
    // we'll update for all account nums, because sometimes account #0 may not be used, only #1 onwards. This should be harmless.
    // we used to do only altemailaddrs, but now also include the name.
    updateUserInfo(request);

    String accountType = request.getParameter("accountType" + accountNum);
    if (Util.nullOrEmpty(accountType)) {
        result.put("status", 1);
        result.put("errorMessage", "No information for account #" + accountNum);
        return result;
    }

    String loginName = request.getParameter("loginName" + accountNum);
    String password = request.getParameter("password" + accountNum);
    String protocol = request.getParameter("protocol" + accountNum);
    //   String port = request.getParameter("protocol" + accountNum);  // we don't support pop/imap on custom ports currently. can support server.com:port syntax some day
    String server = request.getParameter("server" + accountNum);
    String defaultFolder = request.getParameter("defaultFolder" + accountNum);

    if (server != null)
        server = server.trim();

    if (loginName != null)
        loginName = loginName.trim();

    // for these ESPs, the user may have typed in the whole address or just his/her login name
    if (accountType.equals("gmail") && loginName.indexOf("@") < 0)
        loginName = loginName + "@gmail.com";
    if (accountType.equals("yahoo") && loginName.indexOf("@") < 0)
        loginName = loginName + "@yahoo.com";
    if (accountType.equals("live") && loginName.indexOf("@") < 0)
        loginName = loginName + "@live.com";
    if (accountType.equals("stanford") && loginName.indexOf("@") < 0)
        loginName = loginName + "@stanford.edu";
    if (accountType.equals("gmail"))
        server = "imap.gmail.com";

    // add imapdb stuff here.
    boolean imapDBLookupFailed = false;
    String errorMessage = "";
    int errorStatus = 0;

    if (accountType.equals("email") && Util.nullOrEmpty(server)) {
        log.info("accountType = email");

        defaultFolder = "Sent";

        {
            // ISPDB from Mozilla
            imapDBLookupFailed = true;

            String emailDomain = loginName.substring(loginName.indexOf("@") + 1);
            log.info("Domain: " + emailDomain);

            // from http://suhothayan.blogspot.in/2012/05/how-to-install-java-cryptography.html
            // to get around the need for installingthe unlimited strength encryption policy files.
            try {
                Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
                field.setAccessible(true);
                field.set(null, java.lang.Boolean.FALSE);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            //            URL url = new URL("https://live.mozillamessaging.com/autoconfig/v1.1/" + emailDomain);
            URL url = new URL("https://autoconfig.thunderbird.net/v1.1/" + emailDomain);
            try {
                URLConnection urlConnection = url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(in);

                NodeList configList = doc.getElementsByTagName("incomingServer");
                log.info("configList.getLength(): " + configList.getLength());

                int i;
                for (i = 0; i < configList.getLength(); i++) {
                    Node config = configList.item(i);
                    NamedNodeMap attributes = config.getAttributes();
                    if (attributes.getNamedItem("type").getNodeValue().equals("imap")) {
                        log.info("[" + i + "] type: " + attributes.getNamedItem("type").getNodeValue());
                        Node param = config.getFirstChild();
                        String nodeName, nodeValue;
                        String paramHostName = "";
                        String paramUserName = "";
                        do {
                            if (param.getNodeType() == Node.ELEMENT_NODE) {
                                nodeName = param.getNodeName();
                                nodeValue = param.getTextContent();
                                log.info(nodeName + "=" + nodeValue);
                                if (nodeName.equals("hostname")) {
                                    paramHostName = nodeValue;
                                } else if (nodeName.equals("username")) {
                                    paramUserName = nodeValue;
                                }
                            }
                            param = param.getNextSibling();
                        } while (param != null);

                        log.info("paramHostName = " + paramHostName);
                        log.info("paramUserName = " + paramUserName);

                        server = paramHostName;
                        imapDBLookupFailed = false;
                        if (paramUserName.equals("%EMAILADDRESS%")) {
                            // Nothing to do with loginName
                        } else if (paramUserName.equals("%EMAILLOCALPART%")
                                || paramUserName.equals("%USERNAME%")) {
                            // Cut only local part
                            loginName = loginName.substring(0, loginName.indexOf('@') - 1);
                        } else {
                            imapDBLookupFailed = true;
                            errorMessage = "Invalid auto configuration";
                        }

                        break; // break after find first IMAP host name
                    }
                }
            } catch (Exception e) {
                Util.print_exception("Exception trying to read ISPDB", e, log);
                errorStatus = 2; // status code = 2 => ispdb lookup failed
                errorMessage = "No automatic configuration available for " + emailDomain
                        + ", please use the option to provide a private (IMAP) server. \nDetails: "
                        + e.getMessage()
                        + ". \nRunning with java -Djavax.net.debug=all may provide more details.";
            }
        }
    }

    if (imapDBLookupFailed) {
        log.info("ISPDB Fail");
        result.put("status", errorStatus);
        result.put("errorMessage", errorMessage);
        // add other fields here if needed such as server name attempted to be looked up in case the front end wants to give a message to the user
        return result;
    }

    boolean isServerAccount = accountType.equals("gmail") || accountType.equals("email")
            || accountType.equals("yahoo") || accountType.equals("live") || accountType.equals("stanford")
            || accountType.equals("gapps") || accountType.equals("imap") || accountType.equals("pop")
            || accountType.startsWith("Thunderbird");

    if (isServerAccount) {
        boolean sentOnly = "on".equals(request.getParameter("sent-messages-only"));
        return m.addServerAccount(server, protocol, defaultFolder, loginName, password, sentOnly);
    } else if (accountType.equals("mbox") || accountType.equals("tbirdLocalFolders")) {
        try {
            String mboxDir = request.getParameter("mboxDir" + accountNum);
            String emailSource = request.getParameter("emailSource" + accountNum);
            // for non-std local folders dir, tbird prefs.js has a line like: user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb");
            log.info("adding mbox account: " + mboxDir);
            errorMessage = m.addMboxAccount(emailSource, mboxDir, accountType.equals("tbirdLocalFolders"));
            if (!Util.nullOrEmpty(errorMessage)) {
                result.put("errorMessage", errorMessage);
                result.put("status", 1);
            } else
                result.put("status", 0);
        } catch (MboxFolderNotReadableException e) {
            result.put("errorMessage", e.getMessage());
            result.put("status", 1);
        }
    } else {
        result.put("errorMessage", "Sorry, unknown account type: " + accountType);
        result.put("status", 1);
    }
    return result;
}

From source file:Main.java

/**
 * Method to convert a NODE XML to a string.
 * @param n node XML to input.//from   w  w  w . j av a  2  s .  co  m
 * @return string of the node n.
 */
public static String convertElementToString(Node n) {
    String name = n.getNodeName();
    short type = n.getNodeType();
    if (Node.CDATA_SECTION_NODE == type) {
        return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
    }
    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;
    NodeList children = n.getChildNodes();
    if (children.getLength() == 0) {
        if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) {
            sb.append(textContent).append("</").append(name).append('>');
            //;
        } else {
            sb.append("/>").append('\n');
        }
    } else {
        sb.append('>').append('\n');
        boolean hasValidChildren = false;
        for (int i = 0; i < children.getLength(); i++) {
            String childToString = convertElementToString(children.item(i));
            if (!"".equals(childToString)) {
                sb.append(childToString);
                hasValidChildren = true;
            }
        }
        if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) {
            sb.append(textContent);
        }
        sb.append("</").append(name).append('>');
    }
    return sb.toString();
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.geosearch.Geosearch.java

private static boolean checkCoreCreationResponse(String createCoreResponse, String coreName)
        throws GeosearchException {
    boolean createdCore = false;

    String errorMessage = null;/*w  w w . j  ava 2  s .c  om*/

    try {
        // parses the response string as XML
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document createCoreResponseXML = db
                .parse(new ByteArrayInputStream(createCoreResponse.getBytes("UTF-8")));

        XPath xpath = XPathFactory.newInstance().newXPath();

        // gets the status, saved and the core nodes
        Node statusNode = (Node) xpath.compile("/response/lst/int[@name='status']")
                .evaluate(createCoreResponseXML, XPathConstants.NODE);
        Node coreNode = (Node) xpath.compile("/response/str[@name='core']").evaluate(createCoreResponseXML,
                XPathConstants.NODE);
        Node savedNode = (Node) xpath.compile("/response/str[@name='saved']").evaluate(createCoreResponseXML,
                XPathConstants.NODE);

        // checks if the status node has the correct value
        String statusString = statusNode.getTextContent();
        createdCore = (Integer.parseInt(statusString) == GEOSEARCH_RESPONSE_OK_CODE);

        // checks if the core node has the same value as the created core name
        String createdCoreName = coreNode.getTextContent();
        createdCore = (createdCore && coreName.equals(createdCoreName));

        // checks if the saved node is present
        createdCore = (createdCore && (savedNode != null));
    } catch (ParserConfigurationException e) {
        errorMessage = "Error al parsear el XML de respuesta";
    } catch (UnsupportedEncodingException e) {
        errorMessage = "Error en la codificacin del XML de respuesta";
    } catch (SAXException e) {
        errorMessage = "Error al parsear el XML de respuesta";
    } catch (IOException e) {
        errorMessage = "Error al parsear el XML de respuesta";
    } catch (XPathExpressionException e) {
        errorMessage = "Respuesta de Geobsquedas vaca o invlida";
    }

    if (errorMessage != null) {
        throw new GeosearchException(errorMessage);
    }

    return createdCore;
}

From source file:Main.java

/** Transform xml element and children into a string
 *
 * @param nd Node root of elements to transform
 * @return String representation of xml//  w w  w  .  j a  v a2  s  . c  o m
 */
public static String elementToString(Node nd, boolean add_newlines) {
    //short type = n.getNodeType();

    if (Node.CDATA_SECTION_NODE == nd.getNodeType()) {
        return "<![CDATA[" + nd.getNodeValue() + "]]&gt;";
    }

    // return if simple element type
    final String name = nd.getNodeName();
    if (name.startsWith("#")) {
        if (name.equals("#text"))
            return nd.getNodeValue();
        return "";
    }

    // output name
    String ret = "<" + name;

    // output attributes
    NamedNodeMap attrs = nd.getAttributes();
    if (attrs != null) {
        for (int idx = 0; idx < attrs.getLength(); idx++) {
            Node attr = attrs.item(idx);
            ret += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"";
        }
    }

    final String text = nd.getTextContent();
    final NodeList child_ndls = nd.getChildNodes();
    String all_child_str = "";

    for (int idx = 0; idx < child_ndls.getLength(); idx++) {
        final String child_str = elementToString(child_ndls.item(idx), add_newlines);
        if ((child_str != null) && (child_str.length() > 0)) {
            all_child_str += child_str;
        }
    }
    if (all_child_str.length() > 0) {
        // output children
        ret += ">" + (add_newlines ? "\n" : " ");
        ret += all_child_str;
        ret += "</" + name + ">";
    } else if ((text != null) && (text.length() > 0)) {
        // output text
        ret += text;
        ret += "</" + name + ">";
    } else {
        // output nothing
        ret += "/>" + (add_newlines ? "\n" : " ");
    }

    return ret;
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

/**
 * Gets <tt>ODataEntity</tt> from the given entry resource.
 *
 * @param resource entry resource./*from   w w w.  j  a v  a 2s  .co  m*/
 * @param defaultBaseURI default base URI.
 * @return <tt>ODataEntity</tt> object.
 */
public static ODataEntity getODataEntity(final EntryResource resource, final URI defaultBaseURI) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        Serializer.entry(resource, writer);
        writer.flush();
        LOG.debug("EntryResource -> ODataEntity:\n{}", writer.toString());
    }

    final URI base = defaultBaseURI == null ? resource.getBaseURI() : defaultBaseURI;

    final ODataEntity entity = resource.getSelfLink() == null ? ODataFactory.newEntity(resource.getType())
            : ODataFactory.newEntity(resource.getType(),
                    URIUtils.getURI(base, resource.getSelfLink().getHref()));

    if (StringUtils.isNotBlank(resource.getETag())) {
        entity.setETag(resource.getETag());
    }

    if (resource.getEditLink() != null) {
        entity.setEditLink(URIUtils.getURI(base, resource.getEditLink().getHref()));
    }

    for (LinkResource link : resource.getAssociationLinks()) {
        entity.addLink(ODataFactory.newAssociationLink(link.getTitle(), base, link.getHref()));
    }

    for (LinkResource link : resource.getNavigationLinks()) {
        final EntryResource inlineEntry = link.getInlineEntry();
        final FeedResource inlineFeed = link.getInlineFeed();

        if (inlineEntry == null && inlineFeed == null) {
            entity.addLink(ODataFactory.newEntityNavigationLink(link.getTitle(), base, link.getHref()));
        } else if (inlineFeed == null) {
            entity.addLink(ODataFactory.newInlineEntity(link.getTitle(), base, link.getHref(), getODataEntity(
                    inlineEntry, inlineEntry.getBaseURI() == null ? base : inlineEntry.getBaseURI())));
        } else {
            entity.addLink(
                    ODataFactory.newInlineEntitySet(link.getTitle(), base, link.getHref(), getODataEntitySet(
                            inlineFeed, inlineFeed.getBaseURI() == null ? base : inlineFeed.getBaseURI())));
        }
    }

    for (LinkResource link : resource.getMediaEditLinks()) {
        entity.addLink(ODataFactory.newMediaEditLink(link.getTitle(), base, link.getHref()));
    }

    for (ODataOperation operation : resource.getOperations()) {
        operation.setTarget(URIUtils.getURI(base, operation.getTarget()));
        entity.addOperation(operation);
    }

    final Element content;
    if (resource.isMediaEntry()) {
        entity.setMediaEntity(true);
        entity.setMediaContentSource(resource.getMediaContentSource());
        entity.setMediaContentType(resource.getMediaContentType());
        content = resource.getMediaEntryProperties();
    } else {
        content = resource.getContent();
    }
    if (content != null) {
        for (Node property : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
            try {
                entity.addProperty(getProperty((Element) property));
            } catch (IllegalArgumentException e) {
                LOG.warn("Failure retrieving EdmType for {}", property.getTextContent(), e);
            }
        }
    }

    return entity;
}