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

private static void findRecursive(Node parent, String name, List<Node> nodes, boolean onlyOne) {
    String nn = parent.getNodeName();
    int off = nn.indexOf(':');
    if (off >= 0) {
        nn = nn.substring(off + 1);/*from ww  w.  ja  v  a  2s  .com*/
    }
    if (nn.equals(name)) {
        nodes.add(parent);
        if (onlyOne) {
            return;
        }
    }
    for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
        findRecursive(child, name, nodes, onlyOne);
        if (onlyOne && (nodes.size() > 0)) {
            return;
        }
    }
}

From source file:Main.java

/**
 * Trim all new lines from text nodes.//from w  w  w  .  jav a 2s.c  om
 *
 * @param node
 */
public static void normalize(Node node) {
    if (node.getNodeType() == Node.TEXT_NODE) {
        String data = ((Text) node).getData();
        if (data.length() > 0) {
            char ch = data.charAt(data.length() - 1);
            if (ch == '\n' || ch == '\r' || ch == ' ') {
                String data2 = trim(data);
                ((Text) node).setData(data2);
            }
        }
    }
    for (Node currentChild = node.getFirstChild(); currentChild != null; currentChild = currentChild
            .getNextSibling()) {
        normalize(currentChild);
    }
}

From source file:XMLReader.java

/** Returns element value
 * @param elem element (it is XML tag)/*  ww w .java 2s  .c o m*/
 * @return Element value otherwise empty String
 */
private final static String getElementValue(Node elem) {
    Node kid;
    if (elem != null) {
        if (elem.hasChildNodes()) {
            for (kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling()) {
                if (kid.getNodeType() == Node.TEXT_NODE) {
                    return kid.getNodeValue();
                }
            }
        }
    }
    return "";
}

From source file:com.nexmo.insight.sdk.NexmoInsightClient.java

private static InsightResult parseInsightResult(Element root) throws IOException {
    String requestId = null;//from   w  w w.j  a  v a 2s . c o m
    String number = null;
    float price = -1;
    float balance = -1;
    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 ("requestId".equals(name)) {
            requestId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("number".equals(name)) {
            number = 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 = InsightResult.STATUS_INTERNAL_ERROR;
            }
        } else if ("requestPrice".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            try {
                if (str != null)
                    price = Float.parseFloat(str);
            } catch (NumberFormatException e) {
                log.error("xml parser .. invalid value in <requestPrice> node [ " + str + " ] ");
            }
        } else if ("remainingBalance".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            try {
                if (str != null)
                    balance = Float.parseFloat(str);
            } catch (NumberFormatException e) {
                log.error("xml parser .. invalid value in <remainingBalance> node [ " + str + " ] ");
            }
        } else if ("errorText".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 == InsightResult.STATUS_THROTTLED
            || status == InsightResult.STATUS_INTERNAL_ERROR);

    return new InsightResult(status, requestId, number, price, balance, errorText, temporaryError);
}

From source file:org.jboss.seam.forge.shell.util.PluginUtil.java

public static File downloadPlugin(final PluginRef ref, final PipeOut out, final String targetPath)
        throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    String[] artifactParts = ref.getArtifact().split(":");

    if (artifactParts.length != 3) {
        throw new RuntimeException("malformed artifact identifier "
                + "(format should be: <maven.group>:<maven.artifact>:<maven.version>) encountered: "
                + ref.getArtifact());/*from ww w  .jav a 2 s  . c  o  m*/
    }

    String packageLocation = artifactParts[0].replaceAll("\\.", "/");
    String baseUrl;
    if (ref.getHomeRepo().endsWith("/")) {
        baseUrl = ref.getHomeRepo() + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    } else {
        baseUrl = ref.getHomeRepo() + "/" + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    }

    HttpGet httpGetManifest = new HttpGet(baseUrl + "/maven-metadata.xml");
    out.print("Retrieving artifact manifest ... ");

    HttpResponse response = client.execute(httpGetManifest);
    switch (response.getStatusLine().getStatusCode()) {
    case 200:
        out.println("done.");

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getEntity().getContent());

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression checkSnapshotExpr = xpath.compile("//versioning/snapshot");
        XPathExpression findJar = xpath.compile("//snapshotVersion[extension='jar']/value");

        NodeList list = (NodeList) checkSnapshotExpr.evaluate(document, XPathConstants.NODESET);

        out.print("Reading manifest ... ");

        if (list.getLength() != 0) {

            Node n = (Node) findJar.evaluate(document, XPathConstants.NODE);

            if (n == null) {
                out.println("failed: could not determine where to find jar file.");
                return null;
            }

            String version = n.getFirstChild().getTextContent();

            // plugin definition points to a snapshot.
            out.println("good! (maven snapshot found): " + version);

            String fileName = artifactParts[1] + "-" + version + ".jar";

            HttpGet jarGet = new HttpGet(baseUrl + "/" + fileName);

            out.print("Downloading: " + baseUrl + "/" + fileName + " ... ");
            response = client.execute(jarGet);

            try {
                File file = saveFile(targetPath + "/" + fileName, response.getEntity().getContent());
                out.println("done.");
                return file;
            } catch (IOException e) {
                out.println("failed to download: " + e.getMessage());
                return null;
            }

            // do download of snapshot.
        } else {
            out.println("error! (maven snapshot not found)");
            return null;
        }

    case 404:
        String requestUrl = baseUrl + "/" + artifactParts[2] + ".pom";
        httpGetManifest = new HttpGet(requestUrl);
        response = client.execute(httpGetManifest);

        if (response.getStatusLine().getStatusCode() != 200) {
            printError(response.getStatusLine().getStatusCode(), requestUrl, out);
            return null;
        } else {

            // download regular POM here.

        }
        break;
    default:
        out.println("failed! (server returned status code: " + response.getStatusLine().getStatusCode());
        return null;
    }

    return null;

}

From source file:Main.java

/**
 *  Gets the node value as time./*from  w  w w  .j a  v a2  s  .com*/
 *
 *@param  node              Description of the Parameter
 *@return                   The nodeValueAsTime value
 *@exception  DOMException  Description of the Exception
 */
public final static long getNodeValueAsTime(Node node) throws DOMException {
    if (node == null)
        return -1;

    NamedNodeMap attrs = node.getAttributes();
    Node attr = attrs.getNamedItem("Unit");
    int factor = 1;
    String unit = attr.getNodeValue();
    if (unit.equals("sec")) {
        factor = 1000;
    } else if (unit.equals("min")) {
        factor = 60000;
    } else if (unit.equals("hr")) {
        factor = 3600000;
    } else if (unit.equals("day")) {
        factor = 86400000;
    }

    node = node.getFirstChild();
    if (node != null) {
        String time = node.getNodeValue().trim();
        return Integer.parseInt(time) * factor;
    }
    return -1;
}

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

public static String getPatientIDFromWsse(String mtom)
        throws IOException, MessagingException, SAXException, ParserConfigurationException {
    String wsseHeader = Parsing.getWsseHeaderFromMTOM(mtom);
    if (wsseHeader == null)
        return ""; // NOSAML
    String patientId = null;/*w ww .  j ava 2 s  . co  m*/
    //  Node security = JAXB.unmarshal(new StringReader(wsseHeader), Node.class);
    Node securityDoc = MiscUtil.stringToDom(wsseHeader);

    Node security = securityDoc.getFirstChild();

    NodeList securityChildren = security.getChildNodes();
    for (int i = 0; i < securityChildren.getLength(); i++) {
        Node securityChild = securityChildren.item(i);
        if (securityChild.getLocalName() != null && securityChild.getLocalName().equals("Assertion")
                && securityChild.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
            Node assertion = securityChild;
            NodeList assertionChildren = assertion.getChildNodes();
            for (int j = 0; j < assertionChildren.getLength(); j++) {
                Node assertionChild = assertionChildren.item(j);

                if (assertionChild.getLocalName().equals("AttributeStatement")
                        && assertionChild.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
                    Node attributeStatement = assertionChild;
                    NodeList attributeStatementChildren = attributeStatement.getChildNodes();
                    for (int k = 0; k < attributeStatementChildren.getLength(); k++) {
                        Node attributeStatementChild = attributeStatementChildren.item(k);
                        if (attributeStatementChild.getLocalName().equals("Attribute")
                                && attributeStatementChild.getNamespaceURI()
                                        .equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
                            Element attribute = (Element) attributeStatementChild;
                            if (attribute.getAttribute("Name")
                                    .equals("urn:oasis:names:tc:xacml:2.0:resource:resource-id")) {
                                NodeList attributeChildren = attribute.getChildNodes();
                                for (int l = 0; l < attributeChildren.getLength(); l++) {
                                    Node attributeChild = attributeChildren.item(l);
                                    if (attributeChild.getLocalName().equals("AttributeValue")
                                            && attributeChild.getNamespaceURI()
                                                    .equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
                                        Node attributeValue = attributeChild;
                                        return attributeValue.getFirstChild().getNodeValue();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return patientId;
}

From source file:Main.java

/**
 * @param parentNode/*  www .ja  v  a2 s .c  o m*/
 *            is the element tag that contains all the AttirbuteValuePair
 *            tags as children
 * @return Map Returns the AV pairs in a Map where each entry in the Map is
 *         an AV pair. The key is the attribute name and the value is a Set
 *         of String objects.
 */
public static Map parseAttributeValuePairTags(Node parentNode) {

    NodeList avList = parentNode.getChildNodes();
    Map map = null;
    final int numAVPairs = avList.getLength();
    if (numAVPairs <= 0) {
        return EMPTY_MAP;
    }
    for (int l = 0; l < numAVPairs; l++) {
        Node avPair = avList.item(l);
        if ((avPair.getNodeType() != Node.ELEMENT_NODE) || !avPair.getNodeName().equals("AttributeValuePair")) {
            continue;
        }
        NodeList leafNodeList = avPair.getChildNodes();
        long numLeafNodes = leafNodeList.getLength();
        if (numLeafNodes < 2) {
            // TODO: More error handling required later for missing
            // 'Attribute' or
            // 'Value' tags.
            continue;
        }
        String key = null;
        Set values = null;
        // Since Attribute tag is always the first leaf node as per the
        // DTD,and
        // values can one or more, Attribute tag can be parsed first and
        // then
        // iterate over the values, if any.
        Node attributeNode = null;
        for (int i = 0; i < numLeafNodes; i++) {
            attributeNode = leafNodeList.item(i);
            if ((attributeNode.getNodeType() == Node.ELEMENT_NODE)
                    && (attributeNode.getNodeName().equals("Attribute"))) {
                i = (int) numLeafNodes;
            } else {
                continue;
            }
        }
        key = ((Element) attributeNode).getAttribute("name");
        // Now parse the Value tags. If there are not 'Value' tags, ignore
        // this key
        // TODO: More error handling required later for zero 'Value' tags.
        for (int m = 0; m < numLeafNodes; m++) {
            Node valueNode = leafNodeList.item(m);
            if ((valueNode.getNodeType() != Node.ELEMENT_NODE) || !valueNode.getNodeName().equals("Value")) {
                // TODO: Error handling required here
                continue;
            }
            if (values == null) {
                values = new HashSet();
            }
            Node fchild = (Text) valueNode.getFirstChild();
            if (fchild != null) {
                String value = fchild.getNodeValue();
                if (value != null) {
                    values.add(value.trim());
                }
            }
        }
        if (values == null) {
            // No 'Value' tags found. So ignore this key.
            // TODO: More error handling required later for zero
            // 'Value'tags.
            continue;
        }
        if (map == null) {
            map = new HashMap();
        }
        Set oldValues = (Set) map.get(key);
        if (oldValues != null)
            values.addAll(oldValues);
        map.put(key, values);

        // now reset values to prepare for the next AV pair.
        values = null;
    }
    if (map == null) {
        return EMPTY_MAP;
    } else {
        return map;
    }

}

From source file:Main.java

/**
 * @param parentNode/*from w w w .j  a v a 2 s.  c  o  m*/
 *            is the element tag that contains all the AttirbuteValuePair
 *            tags as children
 * @return Map Returns the AV pairs in a Map where each entry in the Map is
 *         an AV pair. The key is the attribute name and the value is a Set
 *         of String objects.
 */
public static Map<String, Set<String>> parseAttributeValuePairTags(Node parentNode) {
    NodeList keyValueList = parentNode.getChildNodes();
    int keyValueSize = keyValueList.getLength();

    if (keyValueSize <= 0) {
        return EMPTY_MAP;
    }

    Map<String, Set<String>> resultMap = null;

    for (int l = 0; l < keyValueSize; l++) {
        Node keyValueNode = keyValueList.item(l);

        if (keyValueNode.getNodeType() != Node.ELEMENT_NODE
                || !keyValueNode.getNodeName().equals("AttributeValuePair")) {
            continue;
        }

        NodeList keyValueEntryList = keyValueNode.getChildNodes();
        int keyValueEntrySize = keyValueEntryList.getLength();
        if (keyValueEntrySize < 2) {
            // TODO: More error handling required later for missing
            // 'Attribute' or 'Value' tags.
            continue;
        }

        Node keyNode = null;

        // Since Attribute tag is always the first leaf node as per the DTD, and values can one or more,
        // Attribute tag can be parsed first and then iterate over the values, if any.
        for (int i = 0; i < keyValueEntrySize; i++) {
            keyNode = keyValueEntryList.item(i);

            if (keyNode.getNodeType() == Node.ELEMENT_NODE && keyNode.getNodeName().equals("Attribute")) {
                break;
            }
        }

        final String key = ((Element) keyNode).getAttribute("name");
        Set<String> values = null;

        // Now parse the Value tags. If there are not 'Value' tags, ignore this key
        // TODO: More error handling required later for zero 'Value' tags.
        for (int m = 0; m < keyValueEntrySize; m++) {
            Node valueNode = keyValueEntryList.item(m);

            if (valueNode.getNodeType() != Node.ELEMENT_NODE || !valueNode.getNodeName().equals("Value")) {
                // TODO: Error handling required here
                continue;
            }

            if (values == null) {
                values = new HashSet<String>();
            }

            Node firstChild = valueNode.getFirstChild();
            if (firstChild != null) {
                String value = firstChild.getNodeValue();

                if (value != null) {
                    values.add(value.trim());
                }
            }
        }

        if (values == null) {
            // No 'Value' tags found. So ignore this key.
            // TODO: More error handling required later for zero
            // 'Value' tags.
            continue;
        }

        if (resultMap == null) {
            resultMap = new HashMap<String, Set<String>>();
        }

        Set<String> oldValues = resultMap.get(key);
        if (oldValues != null) {
            values.addAll(oldValues);
        }
        resultMap.put(key, values);
    }

    return resultMap == null ? EMPTY_MAP : resultMap;
}

From source file:com.puppycrawl.tools.checkstyle.XDocsPagesTest.java

private static Node getFirstChildElement(Node node) {
    for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() != Node.TEXT_NODE) {
            return child;
        }// w  w w .  j a  va2 s. c om
    }

    return null;
}