Example usage for org.w3c.dom Node getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:Main.java

@SuppressWarnings("fallthrough")
private static void getSetRec(final Node rootNode, final Set<Node> result, final Node exclude,
        final boolean com) {
    if (rootNode == exclude) {
        return;//  w  w  w. jav  a2 s.  c om
    }
    switch (rootNode.getNodeType()) {
    case Node.ELEMENT_NODE:
        result.add(rootNode);
        Element el = (Element) rootNode;
        if (el.hasAttributes()) {
            NamedNodeMap nl = el.getAttributes();
            for (int i = 0; i < nl.getLength(); i++) {
                result.add(nl.item(i));
            }
        }
        //no return keep working
    case Node.DOCUMENT_NODE:
        for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) {
            if (r.getNodeType() == Node.TEXT_NODE) {
                result.add(r);
                while (r != null && r.getNodeType() == Node.TEXT_NODE) {
                    r = r.getNextSibling();
                }
                if (r == null) {
                    return;
                }
            }
            getSetRec(r, result, exclude, com);
        }
        return;
    case Node.COMMENT_NODE:
        if (com) {
            result.add(rootNode);
        }
        return;
    case Node.DOCUMENT_TYPE_NODE:
        return;
    default:
        result.add(rootNode);
    }
}

From source file:Main.java

private static void getSetRec(final Node rootNode, final Set<Node> result, final Node exclude,
        final boolean com) {
    if (rootNode == exclude) {
        return;//from  w  w w .j  av  a 2 s.c  o m
    }
    switch (rootNode.getNodeType()) {
    case Node.ELEMENT_NODE:
        result.add(rootNode);
        Element el = (Element) rootNode;
        if (el.hasAttributes()) {
            NamedNodeMap nl = el.getAttributes();
            for (int i = 0; i < nl.getLength(); i++) {
                result.add(nl.item(i));
            }
        }
        //no return keep working
    case Node.DOCUMENT_NODE:
        for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) {
            if (r.getNodeType() == Node.TEXT_NODE) {
                result.add(r);
                while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) {
                    r = r.getNextSibling();
                }
                if (r == null) {
                    return;
                }
            }
            getSetRec(r, result, exclude, com);
        }
        return;
    case Node.COMMENT_NODE:
        if (com) {
            result.add(rootNode);
        }
        return;
    case Node.DOCUMENT_TYPE_NODE:
        return;
    default:
        result.add(rootNode);
    }
}

From source file:org.aectann.postage.TrackingStatusRefreshTask.java

public static TrackingInfo syncRequest(Context context, String tracking) throws FactoryConfigurationError {
    TrackingInfo result = null;/*from   w w w.ja v a 2s.  c  o  m*/
    if (tracking != null && tracking.length() > 0) {
        tracking = tracking.toUpperCase();
        HttpClient client = new DefaultHttpClient();
        try {
            HttpResponse response = client.execute(new HttpGet("http://prishlo.li/" + tracking + ".xml"));
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream content = response.getEntity().getContent();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(content);
                String weight = getFirstVaueOrNull(document, "weight");
                String from = getFirstVaueOrNull(document, "from");
                String kind = getFirstVaueOrNull(document, "kind");
                TrackingInfo old = TrackingStorageUtils.loadStoredTrackingInfo(tracking, context);
                result = new TrackingInfo(old != null ? old.getName() : null, tracking, weight, kind, from);
                NodeList checkpoints = document.getElementsByTagName("checkpoint");

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                for (int i = 0; i < checkpoints.getLength(); i++) {
                    Node current = checkpoints.item(i);
                    NamedNodeMap attributes = current.getAttributes();
                    Node state = attributes.getNamedItem("state");
                    Node attribute = attributes.getNamedItem("attribute");
                    Node date = attributes.getNamedItem("date");

                    String dateString = date.getNodeValue();
                    String attributeString = attribute.getNodeValue();
                    String stateString = state.getNodeValue();
                    String locationString = current.getFirstChild().getNodeValue();
                    result.addStatus(new TrackingStatus(stateString, dateFormat.parse(dateString),
                            attributeString, locationString));
                }
            }
        } catch (Exception e) {
            if (result == null) {
                result = new TrackingInfo(null, tracking, null, null, null);
            }
        }
    }
    return result;
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

private static org.w3c.dom.Node nextNode(org.w3c.dom.Node node) {
    // assert(node != null);
    org.w3c.dom.Node child = node.getFirstChild();

    if (child != null) {
        return child;
    }/* w  w w.j a  v a 2s .  c o  m*/

    org.w3c.dom.Node sib;

    while ((sib = node.getNextSibling()) == null) {
        node = node.getParentNode();

        if (node == null) {
            // End of document
            return null;
        }
    }

    return sib;
}

From source file:com.ephesoft.dcma.util.XMLUtil.java

/**
 * @param doc {@link org.w3c.dom.Document}
 * @param xPathExpression {@link String}
 * @return//  w  w  w.j  a va2s .c  o m
 */
public static String getValueFromXML(final Document doc, final String xPathExpression)
        throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String requiredValue = "";
    XPathExpression expr = xpath.compile(xPathExpression);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    Node item = nodes.item(0);
    if (item != null) {
        requiredValue = item.getFirstChild().getNodeValue();
    }
    return requiredValue;
}

From source file:ValidateLicenseHeaders.java

/**
 * Get all non-comment content from the element.
 * //from   www.  j  av  a 2  s  .c  om
 * @param element
 * @return the concatenated text/cdata content
 */
public static String getElementContent(Element element) {
    if (element == null)
        return null;

    NodeList children = element.getChildNodes();
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
            result.append(child.getNodeValue());
        } else if (child.getNodeType() == Node.COMMENT_NODE) {
            // Ignore comment nodes
        } else {
            result.append(child.getFirstChild());
        }
    }
    return result.toString().trim();
}

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 .j a v a  2s  .  c o  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:com.xpn.xwiki.plugin.feed.SyndEntryDocumentSource.java

/**
 * Extracts the first characters of the given HTML fragment, up to the given length limit, adding only characters in
 * HTML text nodes. The HTML fragment is cleaned up before extracting the prefix to be sure the result is
 * well-formed.//from  w w w.  j av  a2 s  . c  o m
 * 
 * @param htmlFragment the full HTML text
 * @param previewLength the maximum number of characters allowed in the preview, considering only the HTML text
 *            nodes
 * @return a prefix of the given HTML fragment summing at most <code>previewLength</code> characters in its text
 *         nodes
 */
public static String getHTMLPreview(String htmlFragment, int previewLength) {
    try {
        org.w3c.dom.Document html = tidy(htmlFragment, TIDY_HTML_CONFIG);
        Node body = html.getElementsByTagName("body").item(0);
        return XMLUtils.extractXML(body.getFirstChild(), 0, previewLength);
    } catch (RuntimeException e) {
        return getPlainPreview(htmlFragment, previewLength);
    }
}

From source file:Main.java

/**
 * @param n1 first Node to test//w  ww. j a  v  a2s .c o m
 * @param n2 second Node to test
 * @return true if a deep compare show the same children and attributes in
 * the same order
 */
public static boolean equals(Node n1, Node n2) {
    // compare type
    if (!n1.getNodeName().equals(n2.getNodeName())) {
        return false;
    }
    // compare attributes
    NamedNodeMap nnm1 = n1.getAttributes();
    NamedNodeMap nnm2 = n2.getAttributes();
    if (nnm1.getLength() != nnm2.getLength()) {
        return false;
    }
    for (int i = 0; i < nnm1.getLength(); i++) {
        Node attr1 = nnm1.item(i);
        if (!getAttribute(n1, attr1.getNodeName()).equals(getAttribute(n2, attr1.getNodeName()))) {
            return false;
        }
    }
    // compare children
    Node c1 = n1.getFirstChild();
    Node c2 = n2.getFirstChild();
    for (;;) {
        while ((c1 != null) && c1.getNodeName().startsWith("#")) {
            c1 = c1.getNextSibling();
        }
        while ((c2 != null) && c2.getNodeName().startsWith("#")) {
            c2 = c2.getNextSibling();
        }
        if ((c1 == null) && (c2 == null)) {
            break;
        }
        if ((c1 == null) || (c2 == null)) {
            return false;
        }
        if (!equals(c1, c2)) {
            return false;
        }
        c1 = c1.getNextSibling();
        c2 = c2.getNextSibling();
    }
    return true;
}

From source file:it.cnr.icar.eric.server.common.Utility.java

/**
 * This is an implementation of the JAXP DOM Node.setTextContent
 * method, which does not exist in JDK 1.4. This code was adapted
 * from the Apache Xerces 2.8.0 implementation of this method.
 *///from   w  w w. ja v  a 2s. c  o  m
public static void setTextContent(Node node, String textContent) throws DOMException {
    Node child;

    // get rid of any existing children
    while ((child = node.getFirstChild()) != null) {
        node.removeChild(child);
    }

    // create a Text node to hold the given content
    if (textContent != null && textContent.length() != 0) {
        node.appendChild(node.getOwnerDocument().createTextNode(textContent));
    }
}