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

static final void getSetRec(final Node rootNode, final Set result, final Node exclude, final boolean com) {
    //Set result = new HashSet();
    if (rootNode == exclude) {
        return;//from   w w w .j a  va  2s .  c om
    }
    switch (rootNode.getNodeType()) {
    case Node.ELEMENT_NODE:
        result.add(rootNode);
        Element el = (Element) rootNode;
        if (el.hasAttributes()) {
            NamedNodeMap nl = ((Element) rootNode).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);
    }
    return;
}

From source file:com.gatf.executor.validator.ResponseValidator.java

public static String getXMLNodeValue(Node node) {
    String xmlValue = null;//  w w  w .j  a v a 2  s .co m
    if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {
        xmlValue = node.getNodeValue();
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        xmlValue = ((Attr) node).getValue();
    } else if (node.getNodeType() == Node.ELEMENT_NODE && node.getChildNodes().getLength() >= 1
            && (node.getFirstChild().getNodeType() == Node.TEXT_NODE
                    || node.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE)) {
        xmlValue = node.getFirstChild().getNodeValue();
    }
    return xmlValue;
}

From source file:com.l2jfree.gameserver.model.zone.form.Shape.java

public static Shape parseShape(Node sn, int zoneId) {
    String type = "";
    Shape shape = null;//from   ww w  . ja v a  2s  .c  o  m
    Class<?> clazz;
    Constructor<?> constructor;
    try {
        type = sn.getAttributes().getNamedItem("type").getNodeValue();
        clazz = Class.forName("com.l2jfree.gameserver.model.zone.form.Shape" + type);
        constructor = clazz.getConstructor();
        shape = (Shape) constructor.newInstance();
    } catch (Exception e) {
        _log.error("Cannot create a Shape" + type + " in zone " + zoneId);
        return null;
    }

    shape._points = new FastList<Tupel>();
    for (Node n = sn.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("point".equalsIgnoreCase(n.getNodeName())) {
            Tupel t = Tupel.parseTupel(n, zoneId);
            if (t != null)
                shape._points.add(t);
            else
                return null;
        }
    }

    if ("Cylinder".equalsIgnoreCase(type)) {
        try {
            int rad = Integer.parseInt(sn.getAttributes().getNamedItem("radius").getNodeValue());
            ((ShapeCylinder) shape).setRadius(rad);
        } catch (Exception e) {
            _log.warn("missing or wrong radius for cylinder in zone " + zoneId);
            return null;
        }
    } else if ("ExCylinder".equalsIgnoreCase(type)) {
        try {
            int innerRad = Integer.parseInt(sn.getAttributes().getNamedItem("innerRadius").getNodeValue());
            int outerRad = Integer.parseInt(sn.getAttributes().getNamedItem("outerRadius").getNodeValue());
            ((ShapeExCylinder) shape).setRadius(innerRad, outerRad);
        } catch (Exception e) {
            _log.warn("missing or wrong radius for cylinder in zone " + zoneId);
            return null;
        }
    }

    Node z1 = sn.getAttributes().getNamedItem("zMin");
    Node z2 = sn.getAttributes().getNamedItem("zMax");
    if (z1 != null && z2 != null) {
        try {
            shape._zMin = Integer.parseInt(z1.getNodeValue());
            shape._zMax = Integer.parseInt(z2.getNodeValue());
            shape._z = true;
        } catch (NumberFormatException nfe) {
            _log.error("zMin or zMax value not a number in zone " + zoneId);
            return null;
        }
    }

    Node ex = sn.getAttributes().getNamedItem("exclude");
    if (ex != null) {
        try {
            shape._exclude = Boolean.parseBoolean(ex.getNodeValue());
        } catch (Exception e) {
            _log.error("Invalid value for exclude in zone " + zoneId);
        }
    }
    Shape result = shape.prepare(zoneId);
    if (result != null) {
        result._points.clear();
        result._points = null;
    }
    return result;
}

From source file:Main.java

@SuppressWarnings("fallthrough")
static final void getSetRec(final Node rootNode, final Set<Node> result, final Node exclude,
        final boolean com) {
    //Set result = new HashSet();
    if (rootNode == exclude) {
        return;/*from 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 = ((Element) rootNode).getAttributes();
            for (int i = 0; i < nl.getLength(); i++) {
                result.add(nl.item(i));
            }
        }
        //no return keep working - ignore fallthrough warning
    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);
    }
    return;
}

From source file:com.xpn.xwiki.plugin.feed.SyndEntryDocumentSource.java

/**
 * Computes the sum of lengths of all the text nodes within the given DOM sub-tree
 * /*  www. j a va2s .  co m*/
 * @param node the root of the DOM sub-tree containing the text
 * @return the sum of lengths of text nodes within the given DOM sub-tree
 */
public static int innerTextLength(Node node) {
    switch (node.getNodeType()) {
    case Node.TEXT_NODE:
        return node.getNodeValue().length();
    case Node.ELEMENT_NODE:
        int length = 0;
        Node child = node.getFirstChild();
        while (child != null) {
            length += innerTextLength(child);
            child = child.getNextSibling();
        }
        return length;
    case Node.DOCUMENT_NODE:
        return innerTextLength(((org.w3c.dom.Document) node).getDocumentElement());
    default:
        return 0;
    }
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

private static SearchResult.VerifyCheck parseVerifyCheck(Element root) throws IOException {
    String code = null;//w  w  w  .  jav  a 2s .c  o m
    SearchResult.VerifyCheck.Status status = null;
    Date dateReceived = null;
    String ipAddress = null;

    NodeList fields = root.getChildNodes();
    for (int i = 0; i < fields.getLength(); i++) {
        Node node = fields.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;

        String name = node.getNodeName();
        if ("code".equals(name)) {
            code = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("status".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            if (str != null) {
                try {
                    status = SearchResult.VerifyCheck.Status.valueOf(str);
                } catch (IllegalArgumentException e) {
                    log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                }
            }
        } else if ("ip_address".equals(name)) {
            ipAddress = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("date_received".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            if (str != null) {
                try {
                    dateReceived = parseDateTime(str);
                } catch (ParseException e) {
                    log.error("xml parser .. invalid value in <date_received> node [ " + str + " ] ");
                }
            }
        }
    }

    if (status == null)
        throw new IOException("Xml Parser - did not find a <status> node");

    return new SearchResult.VerifyCheck(dateReceived, code, status, ipAddress);
}

From source file:org.opencastproject.analytics.impl.AnalyticsServiceImpl.java

/**
 * Get the value of an xml tag. //from   w  ww  .  ja v  a 2s.  c  om
 * 
 * @param sTag
 *          The xml tag to look for and get the first result.
 * @param eElement
 *          The element to check for the tag.
 * @return The value associated with the xml tag.
 */
private static String getTagValue(String sTag, Element eElement) {
    Node nodeValue = eElement.getElementsByTagName(sTag).item(0);
    return nodeValue.getFirstChild().getNodeValue();
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

private static VerifyResult parseVerifyResult(Element root) throws IOException {
    String requestId = null;//from www.j  a va  2  s.  c o m
    int status = -1;
    String errorText = null;

    NodeList fields = root.getChildNodes();
    for (int i = 0; i < fields.getLength(); i++) {
        Node node = fields.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;

        String name = node.getNodeName();
        if ("request_id".equals(name)) {
            requestId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("status".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            try {
                if (str != null)
                    status = Integer.parseInt(str);
            } catch (NumberFormatException e) {
                log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                status = BaseResult.STATUS_INTERNAL_ERROR;
            }
        } else if ("error_text".equals(name)) {
            errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        }
    }

    if (status == -1)
        throw new IOException("Xml Parser - did not find a <status> node");

    // Is this a temporary error ?
    boolean temporaryError = (status == BaseResult.STATUS_THROTTLED
            || status == BaseResult.STATUS_INTERNAL_ERROR);

    return new VerifyResult(status, requestId, errorText, temporaryError);
}

From source file:ch.entwine.weblounge.common.impl.content.page.PageletRendererImpl.java

/**
 * Initializes this pagelet renderer from an XML node that was generated using
 * {@link #toXml()}.//from   w w  w  .ja  va 2s.  c o m
 * 
 * @param node
 *          the pagelet renderer node
 * @param xpath
 *          the xpath processor
 * @throws IllegalStateException
 *           if the pagelet renderer cannot be parsed
 * @see #fromXml(Node)
 * @see #toXml()
 */
public static PageletRenderer fromXml(Node node, XPath xpath) throws IllegalStateException {

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // Identifier
    String id = XPathHelper.valueOf(node, "@id", xpath);
    if (id == null)
        throw new IllegalStateException("Missing id in page template definition");

    // Class
    String className = XPathHelper.valueOf(node, "m:class", xpath);

    // Create the pagelet renderer
    PageletRenderer renderer = null;
    if (className != null) {
        Class<? extends PageletRenderer> c = null;
        try {
            c = (Class<? extends PageletRenderer>) classLoader.loadClass(className);
            renderer = c.newInstance();
            renderer.setIdentifier(id);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(
                    "Implementation " + className + " for pagelet renderer '" + id + "' not found", e);
        } catch (InstantiationException e) {
            throw new IllegalStateException(
                    "Error instantiating impelementation " + className + " for pagelet renderer '" + id + "'",
                    e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Access violation instantiating implementation " + className
                    + " for pagelet renderer '" + id + "'", e);
        } catch (Throwable t) {
            throw new IllegalStateException(
                    "Error loading implementation " + className + " for pagelet renderer '" + id + "'", t);
        }
    } else {
        renderer = new PageletRendererImpl();
        renderer.setIdentifier(id);
    }

    // Renderer url
    NodeList rendererUrlNodes = XPathHelper.selectList(node, "m:renderer", xpath);
    if (rendererUrlNodes.getLength() == 0)
        throw new IllegalStateException("Missing renderer in page template definition");
    for (int i = 0; i < rendererUrlNodes.getLength(); i++) {
        Node rendererUrlNode = rendererUrlNodes.item(i);
        URL rendererUrl = null;
        Node typeNode = rendererUrlNode.getAttributes().getNamedItem("type");
        String type = (typeNode != null) ? typeNode.getNodeValue() : RendererType.Page.toString();
        try {
            rendererUrl = new URL(rendererUrlNode.getFirstChild().getNodeValue());
            renderer.addRenderer(rendererUrl, type);
        } catch (MalformedURLException e) {
            throw new IllegalStateException(
                    "Malformed renderer url in page template definition: " + rendererUrlNode);
        }
    }

    // Composeable
    renderer.setComposeable("true".equals(XPathHelper.valueOf(node, "@composeable", xpath)));

    // Preview mode
    String previewMode = XPathHelper.valueOf(node, "m:preview", xpath);
    if (previewMode != null)
        renderer.setPreviewMode(PagePreviewMode.parse(previewMode));

    // Editor url
    String editorUrlNode = XPathHelper.valueOf(node, "m:editor", xpath);
    try {
        if (editorUrlNode != null) {
            URL editorUrl = new URL(editorUrlNode);
            renderer.setEditor(editorUrl);
        }
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Malformed editor url in page template definition: " + editorUrlNode);
    }

    // client revalidation time
    String recheck = XPathHelper.valueOf(node, "m:recheck", xpath);
    if (recheck != null) {
        try {
            renderer.setClientRevalidationTime(ConfigurationUtils.parseDuration(recheck));
        } catch (NumberFormatException e) {
            throw new IllegalStateException(
                    "The pagelet renderer revalidation time is malformed: '" + recheck + "'");
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException(
                    "The pagelet renderer revalidation time is malformed: '" + recheck + "'");
        }
    }

    // cache expiration time
    String valid = XPathHelper.valueOf(node, "m:valid", xpath);
    if (valid != null) {
        try {
            renderer.setCacheExpirationTime(ConfigurationUtils.parseDuration(valid));
        } catch (NumberFormatException e) {
            throw new IllegalStateException("The pagelet renderer valid time is malformed: '" + valid + "'", e);
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException("The pagelet renderer valid time is malformed: '" + valid + "'", e);
        }
    }

    // name
    String name = XPathHelper.valueOf(node, "m:name", xpath);
    renderer.setName(name);

    // scripts
    NodeList scripts = XPathHelper.selectList(node, "m:includes/m:script", xpath);
    for (int i = 0; i < scripts.getLength(); i++) {
        renderer.addHTMLHeader(ScriptImpl.fromXml(scripts.item(i)));
    }

    // links
    NodeList includes = XPathHelper.selectList(node, "m:includes/m:link", xpath);
    for (int i = 0; i < includes.getLength(); i++) {
        renderer.addHTMLHeader(LinkImpl.fromXml(includes.item(i)));
    }

    return renderer;
}

From source file:Main.java

/**
 * recursively transform the prefix and the namespace of a node where getNamespaceURI is NULL
 * @param node the node to transform/* w w  w  . j av  a2s .  co  m*/
 * @param prefix the new prefix
 * @param namespaceuri the new namespace uri
 * @return the new node with NS and prefix changed
 */
static public Node setPrefixNamespace(Node node, String prefix, String namespaceuri) {
    Node dest = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element e = (Element) node;
        if (e.getNamespaceURI() == null) {

            Element e2 = node.getOwnerDocument().createElementNS(namespaceuri,
                    (prefix != null ? prefix + ':' + e.getLocalName() : e.getLocalName()));
            NamedNodeMap nodes = e.getAttributes();
            for (int i = 0; i < nodes.getLength(); ++i) {
                Attr att = (Attr) (node.getOwnerDocument().importNode(nodes.item(i), true));
                e2.setAttributeNode(att);
            }
            dest = e2;
        } else {
            dest = node.getOwnerDocument().importNode(node, false);
        }
    } else {
        dest = node.getOwnerDocument().importNode(node, false);
    }

    for (Node c = node.getFirstChild(); c != null; c = c.getNextSibling()) {
        dest.appendChild(setPrefixNamespace(c, prefix, namespaceuri));
    }
    return dest;
}