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:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected List<Map<String, Object>> getSummaries(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it/*from   www.  java 2 s  .  c  o  m*/
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();
        nodes = response.getElementsByTagName("DocSum");
        for (int i = 0; i < nodes.getLength(); ++i) {
            Element n = (Element) nodes.item(i);
            Map<String, Object> doc = new HashMap<String, Object>();
            doc.put("id", n.getElementsByTagName("Id").item(0).getTextContent());
            NodeList items = n.getElementsByTagName("Item");
            for (int j = 0; j < items.getLength(); ++j) {
                Element item = (Element) items.item(j);
                if ("List".equals(item.getAttribute("Type"))) {
                    NodeList subitems = item.getElementsByTagName("Item");
                    if (subitems.getLength() > 0) {
                        List<String> values = new ArrayList<String>(subitems.getLength());
                        for (int k = 0; k < subitems.getLength(); ++k) {
                            values.add(subitems.item(k).getTextContent());
                        }
                        doc.put(item.getAttribute("Name"), values);
                    }
                } else {
                    String value = item.getTextContent();
                    if (StringUtils.isNotEmpty(value)) {
                        doc.put(item.getAttribute("Name"), value);
                    }
                }
            }
            result.add(doc);
        }
        return result;
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return Collections.emptyList();
}

From source file:Main.java

private static String getMetaScriptType(Document doc) {
    // Can not just do a Document.getElementsByTagName(String) as this
    // needs//from   ww w. j a  v  a2  s .  com
    // to be relatively fast.
    List metas = new ArrayList();
    // check for META tags under the Document
    Node html = null;
    Node head = null;
    Node child = null;
    // ----------------------------------------------------------------------
    // (pa) 20021217
    // cmvc defect 235554
    // performance enhancement: using child.getNextSibling() rather than
    // nodeList(item) for O(n) vs. O(n*n)
    // ----------------------------------------------------------------------

    for (child = doc.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        if (child.getNodeName().equalsIgnoreCase(META)) {
            metas.add(child);
        } else if (child.getNodeName().equalsIgnoreCase(HTML)) {
            html = child;
        }
    }
    // NodeList children = doc.getChildNodes();
    // for(int i = 0; i < children.getLength(); i++) {
    // child = children.item(i);
    // if(child.getNodeType() != Node.ELEMENT_NODE)
    // continue;
    // if(child.getNodeName().equalsIgnoreCase(META))
    // metas.add(child);
    // else if(child.getNodeName().equalsIgnoreCase(HTML))
    // html = child;
    // }

    // check for META tags under HEAD
    if (html != null) {
        for (child = html.getFirstChild(); (child != null) && (head == null); child = child.getNextSibling()) {
            if (child.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            if (child.getNodeName().equalsIgnoreCase(HEAD)) {
                head = child;
            }
        }
        // children = html.getChildNodes();
        // for(int i = 0; i < children.getLength() && head == null; i++) {
        // child = children.item(i);
        // if(child.getNodeType() != Node.ELEMENT_NODE)
        // continue;
        // if(child.getNodeName().equalsIgnoreCase(HEAD))
        // head = child;
        // }
    }

    if (head != null) {
        for (head.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            if (child.getNodeName().equalsIgnoreCase(META)) {
                metas.add(child);
            }
        }
        // children = head.getChildNodes();
        // for(int i = 0 ; i < children.getLength(); i++) {
        // child = children.item(i);
        // if(child.getNodeType() != Node.ELEMENT_NODE)
        // continue;
        // if(child.getNodeName().equalsIgnoreCase(META))
        // metas.add(child);
        // }
    }

    return getMetaScriptType(metas);
}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

TradingSystem loadTradingSystem(NodeList node) {
    TradingSystem obj = new TradingSystem(
            new Integer(Integer.parseInt(((Node) node).getAttributes().getNamedItem("id").getNodeValue())));

    for (int i = 0; i < node.getLength(); i++) {
        Node item = node.item(i);
        String nodeName = item.getNodeName();
        Node value = item.getFirstChild();
        if (value != null) {
            if (nodeName.equals("name")) //$NON-NLS-1$
                obj.setName(value.getNodeValue());
            else if (nodeName.equals("account")) //$NON-NLS-1$
            {//ww w  .j  a  v a  2 s .  c o  m
                Integer id = new Integer(value.getNodeValue());
                Account account = (Account) CorePlugin.getRepository().load(Account.class, id);
                if (account == null) {
                    log.warn("Unknown account (id=" + id + ")");
                    account = new DefaultAccount(id);
                }
                obj.setAccount(account);
            } else if (nodeName.equals("tradingProvider")) //$NON-NLS-1$
                obj.setTradingProviderId(value.getNodeValue());
        }
        if (nodeName.equals("moneyManager")) //$NON-NLS-1$
            obj.setMoneyManager(loadComponent(item.getChildNodes()));
        else if (nodeName.equalsIgnoreCase("param") == true) {
            NamedNodeMap map = item.getAttributes();
            obj.getParams().put(map.getNamedItem("key").getNodeValue(),
                    map.getNamedItem("value").getNodeValue());
        }
        if (nodeName.equals("strategy")) //$NON-NLS-1$
            obj.addStrategy(loadStrategy(item.getChildNodes()));
    }

    obj.clearChanged();

    return obj;
}

From source file:com.mirth.connect.model.converters.ER7Serializer.java

public Map<String, String> getMetadataFromDocument(Document document) {
    Map<String, String> metadata = new HashMap<String, String>();

    if (useStrictParser) {
        try {/*from   w w  w . ja v  a2 s  .  c  o  m*/
            DocumentSerializer serializer = new DocumentSerializer();
            String source = serializer.toXML(document);
            Message message = xmlParser.parse(source);
            Terser terser = new Terser(message);
            String sendingFacility = terser.get("/MSH-4-1");
            String event = terser.get("/MSH-9-1") + "-" + terser.get("/MSH-9-2");
            metadata.put("version", message.getVersion());
            metadata.put("type", event);
            metadata.put("source", sendingFacility);
            return metadata;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return metadata;
        }
    } else {
        if (document.getElementsByTagName("MSH.4.1").getLength() > 0) {
            Node senderNode = document.getElementsByTagName("MSH.4.1").item(0);

            if ((senderNode != null) && (senderNode.getFirstChild() != null)) {
                metadata.put("source", senderNode.getFirstChild().getTextContent());
            } else {
                metadata.put("source", "");
            }
        }

        if (document.getElementsByTagName("MSH.9").getLength() > 0) {
            if (document.getElementsByTagName("MSH.9.1").getLength() > 0) {
                Node typeNode = document.getElementsByTagName("MSH.9.1").item(0);

                if (typeNode != null) {
                    String type = typeNode.getFirstChild().getNodeValue();

                    if (document.getElementsByTagName("MSH.9.2").getLength() > 0) {
                        Node subTypeNode = document.getElementsByTagName("MSH.9.2").item(0);
                        type += "-" + subTypeNode.getFirstChild().getTextContent();
                    }

                    metadata.put("type", type);
                } else {
                    metadata.put("type", "Unknown");
                }
            }
        }

        if (document.getElementsByTagName("MSH.12.1").getLength() > 0) {
            Node versionNode = document.getElementsByTagName("MSH.12.1").item(0);

            if (versionNode != null) {
                metadata.put("version", versionNode.getFirstChild().getTextContent());
            } else {
                metadata.put("version", "");
            }
        }

        return metadata;
    }
}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

Strategy loadStrategy(NodeList node) {
    NamedNodeMap map = ((Node) node).getAttributes();
    Strategy obj = new Strategy(new Integer(map.getNamedItem("id").getNodeValue()));
    if (map.getNamedItem("pluginId") != null)
        obj.setPluginId(map.getNamedItem("pluginId").getNodeValue());
    if (map.getNamedItem("autostart") != null)
        obj.setAutoStart(map.getNamedItem("autostart").getNodeValue().equals("true"));

    for (int i = 0; i < node.getLength(); i++) {
        Node item = node.item(i);
        String nodeName = item.getNodeName();
        Node value = item.getFirstChild();
        if (value != null) {
            if (nodeName.equals("name")) //$NON-NLS-1$
                obj.setName(value.getNodeValue());
        }/*  w  w w  .  ja va2  s .  c  o  m*/
        if (nodeName.equals("marketManager")) //$NON-NLS-1$
            obj.setMarketManager(loadComponent(item.getChildNodes()));
        else if (nodeName.equals("entry")) //$NON-NLS-1$
            obj.setEntry(loadComponent(item.getChildNodes()));
        else if (nodeName.equals("exit")) //$NON-NLS-1$
            obj.setExit(loadComponent(item.getChildNodes()));
        else if (nodeName.equals("moneyManager")) //$NON-NLS-1$
            obj.setMoneyManager(loadComponent(item.getChildNodes()));
        else if (nodeName.equalsIgnoreCase("security") == true) {
            map = item.getAttributes();
            Integer id = new Integer(map.getNamedItem("id").getNodeValue());
            Security security = (Security) CorePlugin.getRepository().load(Security.class, id);
            if (security == null)
                log.warn("Unknown security (id=" + id + ")");
            else
                obj.addSecurity(security);
        }
        if (nodeName.equalsIgnoreCase("param") == true) {
            map = item.getAttributes();
            obj.getParams().put(map.getNamedItem("key").getNodeValue(),
                    map.getNamedItem("value").getNodeValue());
        }
    }

    obj.clearChanged();

    return obj;
}

From source file:com.l2jfree.gameserver.model.mapregion.L2MapRegionRestart.java

public L2MapRegionRestart(Node node) {
    _restartId = Integer.parseInt(node.getAttributes().getNamedItem("restartId").getNodeValue());
    _name = node.getAttributes().getNamedItem("name").getNodeValue();
    _bbsId = Integer.parseInt(node.getAttributes().getNamedItem("bbs").getNodeValue());
    _locName = Integer.parseInt(node.getAttributes().getNamedItem("locname").getNodeValue());

    for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("normal".equalsIgnoreCase(n.getNodeName())) {
            _restartPoints = ArrayUtils.add(_restartPoints, getLocation(n));
        } else if ("chaotic".equalsIgnoreCase(n.getNodeName())) {
            _chaoticPoints = ArrayUtils.add(_chaoticPoints, getLocation(n));
        } else if ("bannedrace".equalsIgnoreCase(n.getNodeName())) {
            _bannedRace = Race.getRaceByName(n.getAttributes().getNamedItem("race").getNodeValue());
            _bannedRaceRestartId = Integer.parseInt(n.getAttributes().getNamedItem("restartId").getNodeValue());
        }/* w w  w  .j  a  v a  2  s  . c  om*/
    }
}

From source file:gov.nih.nci.cabig.caaers2adeers.track.Tracker.java

private void captureLogDetails(Exchange exchange, IntegrationLog integrationLog) {
    if (caputureLogDetails) {
        //Check for soap fault
        String faultString = XPathBuilder.xpath("//faultstring/text()").evaluate(exchange, String.class);
        if (!StringUtils.isBlank(faultString)) {
            integrationLog.setNotes(SOAP_FAULT_STATUS);
            integrationLog.addIntegrationLogDetail(new IntegrationLogDetail(null, faultString, true));
        }/*w  w w .  j  a v a2  s. c o m*/

        //check for caaers error message in response
        String errorString = XPathBuilder.xpath("//error/text()").evaluate(exchange, String.class);
        if (!StringUtils.isBlank(errorString)) {
            integrationLog.setNotes(CAAERS_RESPONSE_ERROR);
            integrationLog.addIntegrationLogDetail(new IntegrationLogDetail(null, errorString, true));
        }

        //check for 'com:entityProcessingOutcomes'
        NodeList nodes = XPathBuilder.xpath("//com:entityProcessingOutcomes")
                .namespace("com", "http://schema.integration.caaers.cabig.nci.nih.gov/common").nodeResult()
                .evaluate(exchange, NodeList.class);

        if (nodes != null) {

            for (int i = 0; i < nodes.getLength(); i++) {
                Node outcome = nodes.item(i);
                if (StringUtils.equals(outcome.getLocalName(), "entityProcessingOutcome")) {
                    NodeList children = outcome.getChildNodes();
                    String businessIdentifier = null;
                    String outcomeMsg = null;
                    boolean failed = false;
                    for (int j = 0; j < children.getLength(); j++) {
                        Node child = children.item(j);
                        String childLocalName = child.getLocalName();
                        if (!StringUtils.isBlank(childLocalName)
                                && childLocalName.equals("businessIdentifier")) {
                            businessIdentifier = child.getFirstChild().getNodeValue();
                        } else if (!StringUtils.isBlank(childLocalName) && childLocalName.equals("message")) {
                            outcomeMsg = child.getFirstChild() != null ? child.getFirstChild().getNodeValue()
                                    : null;
                        } else if (!StringUtils.isBlank(childLocalName) && childLocalName.equals("failed")) {
                            failed = new Boolean(
                                    child.getFirstChild() != null ? child.getFirstChild().getNodeValue()
                                            : "false");
                        }
                    }
                    if (businessIdentifier != null) {
                        integrationLog.addIntegrationLogDetail(
                                new IntegrationLogDetail(businessIdentifier, outcomeMsg, failed));
                    }
                }
            }
        }
    }
}

From source file:com.amalto.core.save.context.BeforeSaving.java

public void save(SaverSession session, DocumentSaverContext context) {
    // Invoke the beforeSaving
    MutableDocument updateReportDocument = context.getUpdateReportDocument();
    if (updateReportDocument == null) {
        throw new IllegalStateException("Update report is missing."); //$NON-NLS-1$
    }/* www .jav a 2s.  co m*/
    OutputReport outputreport = session.getSaverSource().invokeBeforeSaving(context, updateReportDocument);

    if (outputreport != null) { // when a process was found
        String errorCode;
        message = outputreport.getMessage();
        if (!validateFormat(message))
            throw new BeforeSavingFormatException(message);
        try {
            Document doc = Util.parse(message);
            // handle output_report
            String xpath = "//report/message"; //$NON-NLS-1$
            Node errorNode;
            synchronized (XPATH) {
                errorNode = (Node) XPATH.evaluate(xpath, doc, XPathConstants.NODE);
            }
            errorCode = null;
            if (errorNode instanceof Element) {
                Element errorElement = (Element) errorNode;
                errorCode = errorElement.getAttribute("type"); //$NON-NLS-1$
                Node child = errorElement.getFirstChild();
                if (child instanceof org.w3c.dom.Text) {
                    message = child.getTextContent();
                } else {
                    message = ""; //$NON-NLS-1$   
                }
            }

            if (!"info".equals(errorCode)) { //$NON-NLS-1$
                throw new BeforeSavingErrorException(message);
            }

            // handle output_item
            if (outputreport.getItem() != null) {
                xpath = "//exchange/item"; //$NON-NLS-1$
                SkipAttributeDocumentBuilder builder = new SkipAttributeDocumentBuilder(
                        SaverContextFactory.DOCUMENT_BUILDER, false);
                doc = builder.parse(new InputSource(new StringReader(outputreport.getItem())));
                Node item;
                synchronized (XPATH) {
                    item = (Node) XPATH.evaluate(xpath, doc, XPathConstants.NODE);
                }
                if (item != null && item instanceof Element) {
                    Node node = null;
                    Node current = item.getFirstChild();
                    while (current != null) {
                        if (current instanceof Element) {
                            node = current;
                            break;
                        }
                        current = item.getNextSibling();
                    }
                    if (node != null) {
                        // set back the modified item by the process
                        DOMDocument document = new DOMDocument(node, context.getUserDocument().getType(),
                                context.getDataCluster(), context.getDataModelName());
                        context.setUserDocument(document);
                        context.setDatabaseDocument(null);
                        // Redo a set of actions and security checks.
                        // TMDM-4599: Adds UpdateReport phase so a new update report is generated based on latest changes.
                        next = new ID(
                                new GenerateActions(new Security(new UpdateReport(new ApplyActions(next)))));
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Exception occurred during before saving phase.", e); //$NON-NLS-1$
        }
    }

    next.save(session, context);
}

From source file:com.konakart.actions.gateways.AuthorizeNetBaseAction.java

/**
 * Common code to send a message and receive a response
 * /*from   ww w  .jav a2 s .c om*/
 * @param kkAppEng
 * @param msg
 * @param methodName
 * @param retAttr
 * @param custId
 * @param profileId
 * @return Returns the value of the attribute called retAttr
 * @throws Exception
 */
protected String sendMsgToGateway(KKAppEng kkAppEng, StringBuffer msg, String methodName, String retAttr,
        int custId, String profileId) throws Exception {
    // Get a response from the gateway
    String gatewayResp = getGatewayResponse(msg, methodName);

    // Now process the XML response
    String ret = null;

    if (gatewayResp != null) {
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            ByteArrayInputStream bais = new ByteArrayInputStream(gatewayResp.getBytes());
            Document doc = builder.parse(bais);

            boolean val = validateGatewayResponse(kkAppEng, msg, methodName, custId, profileId, doc);
            if (val) {
                NodeList list = doc.getElementsByTagName(retAttr);
                if (list != null && list.getLength() == 1) {
                    Node node = list.item(0);
                    Text datanode = (Text) node.getFirstChild();
                    ret = datanode.getData();
                }
                if (log.isDebugEnabled()) {
                    log.debug("AuthorizeNet " + methodName + " response data:" + "\n    " + retAttr
                            + "                              = " + ret);
                }
            }
            return ret;

        } catch (Exception e) {
            // Problems parsing the XML
            if (log.isDebugEnabled()) {
                log.debug("Problems parsing AuthorizeNet " + methodName + " response: " + e.getMessage());
            }
            throw e;
        }
    }

    return retAttr;

}

From source file:com.ibm.sbt.test.lib.MockSerializer.java

public HttpResponse replayResponse() throws ClientServicesException {
    try {/*w w w .ja  v a2s. com*/
        Node r = getReader().next();

        NamedNodeMap nnm = r.getAttributes();

        String code = nnm.getNamedItem("statusCode").getTextContent();
        String reason = nnm.getNamedItem("statusReason").getTextContent();

        Node headers = (Node) DOMUtil.evaluateXPath(r, "./headers").getSingleNode();
        Node data = (Node) DOMUtil.evaluateXPath(r, "./data").getSingleNode();
        String entity = null;
        if (data != null) {
            if (data.getFirstChild() == null)
                entity = "";
            else
                entity = ((CharacterData) data.getFirstChild()).getData();
        }
        Iterator<Node> hIt = (Iterator<Node>) DOMUtil.evaluateXPath(headers, "./header").getNodeIterator();
        ArrayList<Header> allHeaders = new ArrayList<Header>();

        while (hIt.hasNext()) {
            Node headerNode = hIt.next();
            String name = ((Node) DOMUtil.evaluateXPath(headerNode, "./name").getSingleNode()).getTextContent();
            String value = ((Node) DOMUtil.evaluateXPath(headerNode, "./value").getSingleNode())
                    .getTextContent();
            allHeaders.add(new BasicHeader(name, value));
        }

        return buildResponse(allHeaders.toArray(new Header[allHeaders.size()]), Integer.valueOf(code), reason,
                entity);

    } catch (FileNotFoundException e) {
        StackTraceElement trace = getStackTraceElement();
        String fullClassName = trace.getClassName();
        String methodName = trace.getMethodName();
        String endpointName = getEndpointName();
        throw new MockingException(e,
                "Mocking file missing for test: " + fullClassName + "." + methodName + "/" + endpointName);
    } catch (Exception e) {
        throw new MockingException(e, "Corrupted Mocking file, please regenerate: " + getPath());
    }
}