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:com.hp.autonomy.searchcomponents.idol.view.IdolViewServerServiceTest.java

private GetContentResponseData mockResponseData() {
    final GetContentResponseData responseData = new GetContentResponseData();

    final Hit hit = new Hit();
    responseData.getHit().add(hit);/*from  www.ja v  a 2  s .  c om*/

    final DocContent content = new DocContent();
    hit.setContent(content);

    final Node node = mock(Node.class);
    content.getContent().add(node);

    final NodeList childNodes = mock(NodeList.class);
    when(childNodes.getLength()).thenReturn(1);
    when(node.getChildNodes()).thenReturn(childNodes);

    final Node referenceNode = mock(Node.class);
    when(referenceNode.getLocalName()).thenReturn(SAMPLE_REFERENCE_FIELD_NAME);

    final Node textNode = mock(Node.class);
    when(textNode.getNodeValue()).thenReturn("http://en.wikipedia.org/wiki/Car");
    when(referenceNode.getFirstChild()).thenReturn(textNode);
    when(childNodes.item(0)).thenReturn(referenceNode);

    return responseData;
}

From source file:org.dozer.eclipse.plugin.sourcepage.validation.Validator.java

@SuppressWarnings("restriction")
private void checkFieldNodes(NodeList nodeList, IFile file, ValidationInfo validationReport)
        throws JavaModelException, DOMException {
    int len = nodeList.getLength();
    //check all field-nodes...
    for (int i = 0; i < len; i++) {
        Node node = nodeList.item(i); //field

        //..have custom-converter attributes
        Node attrNode = node.getAttributes().getNamedItem("custom-converter");
        if (attrNode != null) {
            //...doesnt implement the CustomConverter Interface
            if (!checkClassImplementsCustomConverter(file.getProject(), attrNode.getNodeValue())) {
                //this class doesnt implement the interface and is worth an error
                Integer[] location = (Integer[]) node.getUserData("location");
                validationReport.addError("Class does not implement interface CustomConverter", location[0],
                        location[1], validationReport.getFileURI());
            }//w w  w  .  j  a va2  s . co  m
            //...have custom-converter-id attributes
        } else {
            attrNode = node.getAttributes().getNamedItem("custom-converter-id");
            if (attrNode != null) {
                String className = DozerPluginUtils.getClassNameForCCI(file, attrNode.getNodeValue());
                if (className != null && !checkClassImplementsCustomConverter(file.getProject(), className)) {
                    //this class doesnt implement the interface and is worth an error
                    Integer[] location = (Integer[]) node.getUserData("location");
                    validationReport.addError("Bean does not implement interface CustomConverter", location[0],
                            location[1], validationReport.getFileURI());
                }
            }
        }

        NodeList abList = node.getChildNodes();
        int abLen = abList.getLength();
        for (int a = 0; a < abLen; a++) {
            Node abNode = abList.item(a); //a or b
            if ("a".equals(abNode.getNodeName()) || "b".equals(abNode.getNodeName())) {
                Node textNode = abNode.getFirstChild();
                //...no value set between <a></a> or <b></b>?
                if (textNode == null) {
                    Integer[] location = (Integer[]) node.getUserData("location");
                    String className = DozerPluginUtils.getMappingClassName(abNode);
                    String nodeName = abNode.getNodeName();

                    validationReport.addError(
                            "Unsetted property value in node " + nodeName + " for class " + className,
                            location[0], location[1], validationReport.getFileURI());
                }
                //...is fieldname correct?
                else if (textNode.getNodeType() == Node.TEXT_NODE) {
                    String property = textNode.getNodeValue();
                    String className = DozerPluginUtils.getMappingClassName(abNode);

                    attrNode = DozerPluginUtils.getMappingNode(abNode).getAttributes().getNamedItem("type");
                    boolean bIsBiDirectional = true;
                    if (attrNode != null) {
                        bIsBiDirectional = "bi-directional".equals(attrNode.getNodeValue());
                    }

                    if (!"this".equals(property)) {
                        Node isAccessibleNode = abNode.getAttributes().getNamedItem("is-accessible");
                        boolean isAccessible = isAccessibleNode != null
                                && "true".equals(isAccessibleNode.getNodeValue());

                        if ((bIsBiDirectional || "a".equals(abNode.getNodeName()))
                                && DozerPluginUtils.hasReadProperty(property, className, file.getProject(),
                                        isAccessible) == null) {
                            Integer[] location = (Integer[]) abNode.getUserData("location");
                            validationReport.addError(
                                    "Property " + property + " for class " + className
                                            + " cannot be read from.",
                                    location[0], location[1], validationReport.getFileURI());
                        } else if ((bIsBiDirectional || "b".equals(abNode.getNodeName())) && DozerPluginUtils
                                .hasWriteProperty(property, className, file.getProject()) == null) {
                            Integer[] location = (Integer[]) abNode.getUserData("location");
                            validationReport.addError(
                                    "Property " + property + " for class " + className
                                            + " cannot be written to.",
                                    location[0], location[1], validationReport.getFileURI());
                        }
                    }
                }
            }
        }
    }
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected String getSummariesXML(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 ww w.  j  ava 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());
                }
            }
        }
        Source source = new DOMSource(response);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return "";
}

From source file:de.elbe5.base.data.XmlData.java

public Node findSubElement(Node parent, String localName) {
    if (parent == null) {
        return null;
    }/* w w w .  j  a v  a 2  s  .c  om*/
    Node child = parent.getFirstChild();
    while (child != null) {
        if ((child.getNodeType() == Node.ELEMENT_NODE) && (child.getLocalName().equals(localName))) {
            return child;
        }
        child = child.getNextSibling();
    }
    return null;
}

From source file:com.googlecode.psiprobe.beans.JBossResourceResolverBean.java

public List getApplicationResources() throws NamingException {

    List resources = new ArrayList();

    MBeanServer server = getMBeanServer();
    if (server != null) {
        try {/*from w w  w  .jav a 2  s .  co m*/
            Set dsNames = server.queryNames(new ObjectName("jboss.jca:service=ManagedConnectionPool,*"), null);
            for (Iterator it = dsNames.iterator(); it.hasNext();) {
                ObjectName managedConnectionPoolOName = (ObjectName) it.next();

                ApplicationResource resource = new ApplicationResource();
                resource.setName(managedConnectionPoolOName.getKeyProperty("name"));
                resource.setType("jboss");
                String criteria = (String) server.getAttribute(managedConnectionPoolOName, "Criteria");
                if ("ByApplication".equals(criteria)) {
                    resource.setAuth("Application");
                } else if ("ByContainerAndApplication".equals(criteria)) {
                    resource.setAuth("Both");
                } else {
                    resource.setAuth("Container");
                }
                DataSourceInfo dsInfo = new DataSourceInfo();
                dsInfo.setMaxConnections(
                        ((Integer) server.getAttribute(managedConnectionPoolOName, "MaxSize")).intValue());
                dsInfo.setEstablishedConnections(
                        ((Integer) server.getAttribute(managedConnectionPoolOName, "ConnectionCount"))
                                .intValue());
                dsInfo.setBusyConnections(
                        ((Long) server.getAttribute(managedConnectionPoolOName, "InUseConnectionCount"))
                                .intValue());

                ObjectName connectionFactoryOName = new ObjectName(
                        "jboss.jca:service=ManagedConnectionFactory,name=" + resource.getName());
                Element elm = (Element) server.getAttribute(connectionFactoryOName,
                        "ManagedConnectionFactoryProperties");

                if (elm != null) {
                    NodeList nl = elm.getChildNodes();
                    for (int i = 0; i < nl.getLength(); i++) {
                        Node n = nl.item(i);
                        Node na = n.getAttributes().getNamedItem("name");
                        if (na != null) {
                            if ("ConnectionURL".equals(na.getNodeValue())) {
                                dsInfo.setJdbcURL(n.getFirstChild().getNodeValue());
                            }

                            if ("UserName".equals(na.getNodeValue())) {
                                dsInfo.setUsername(n.getFirstChild().getNodeValue());
                            }

                            //
                            // JMS datasource
                            //
                            if ("JmsProviderAdapterJNDI".equals(na.getNodeValue())) {
                                dsInfo.setJdbcURL(n.getFirstChild().getNodeValue());
                                resource.setType("jms");
                            }
                        }
                    }
                }

                dsInfo.setResettable(true);

                resource.setDataSourceInfo(dsInfo);
                resources.add(resource);
            }
        } catch (Exception e) {
            //
            logger.fatal("There was an error querying JBoss JMX server:", e);
        }
    }
    return resources;
}

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

Component loadComponent(NodeList node) {
    NamedNodeMap map = ((Node) node).getAttributes();
    Component obj = new Component(new Integer(map.getNamedItem("id").getNodeValue()));
    obj.setPluginId(map.getNamedItem("pluginId").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) {
        }// w ww. jav a 2  s .  com
        if (nodeName.equalsIgnoreCase("param") == true) {
            map = item.getAttributes();
            obj.getPreferences().setValue(map.getNamedItem("key").getNodeValue(),
                    map.getNamedItem("value").getNodeValue());
        }
    }

    obj.clearChanged();

    return obj;
}

From source file:com.prowidesoftware.swift.io.parser.XMLParser.java

private String getText(final Node n) {
    String text = null;//from   www.  ja va2s.c o m
    final Node c = n.getFirstChild();
    if (c != null) {
        if (c.getNodeType() == Node.TEXT_NODE) {
            text = c.getNodeValue().trim();
        } else {
            log.warning("Node is not TEXT_NODE: " + c);
        }
    }
    return text;
}

From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java

private List<NZB> fetchFeed(Collection<NameValuePair> params) throws SearchException, DOMException {
    THROTTLER.throttle();//from w ww. ja  v a  2 s.co m
    Document document = null;
    try {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.addAll(params);
        qparams.add(new BasicNameValuePair("dl", "1"));
        URI uri = getUri("rss.php", qparams);
        synchronized (builderSemaphore) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            int attempts = RETRY_ATTEMPTS;
            boolean retry;
            do
                try {
                    retry = false;
                    document = builder.parse(uri.toString());
                } catch (IOException ioe) {
                    if (attempts == 0
                            || !ioe.getMessage().startsWith("Server returned HTTP response code: 503")) {
                        throw ioe;
                    } else {
                        attempts--;
                        retry = true;
                        THROTTLER.throttleBig();
                    }
                }
            while (retry);
        }
    } catch (IOException ioe) {
        throw new SearchException("Error connecting to Nzbs.org.", ioe);
    } catch (SAXException se) {
        throw new SearchException("Error parsing rss from Nzbs.org.", se);
    } catch (ParserConfigurationException pce) {
        throw new SearchException("Error configuring XML parser.", pce);
    } catch (URISyntaxException e) {
        throw new SearchException("Error parsing URI.", e);
    }
    Node rss = document.getFirstChild();
    if (!"rss".equalsIgnoreCase(rss.getNodeName())) {
        throw new SearchException("Result was not RSS but " + rss.getNodeName());
    }
    Node channel = rss.getFirstChild();
    while (channel != null && "#text".equals(channel.getNodeName())) {
        channel = channel.getNextSibling();
    }
    NodeList list = channel.getChildNodes();
    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.CANADA);
    List<NZB> result = new ArrayList<NZB>();
    UrlBasedSupplier supplier = new UrlBasedSupplier();
    supplier.setThrottler(THROTTLER);
    for (int i = 0; i < list.getLength(); i++) {
        Node n = list.item(i);
        if ("item".equals(n.getNodeName())) {
            LazyNZB nzb = new LazyNZB("tmpName", supplier);
            try {
                for (int j = 0; j < n.getChildNodes().getLength(); j++) {
                    Node n2 = n.getChildNodes().item(j);
                    if ("title".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setName(n2.getTextContent());
                        nzb.setFilename(Util.saveFileName(n2.getTextContent()) + ".nzb");
                    }
                    if ("pubdate".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setPostDate(df.parse(n2.getTextContent()));
                    }
                    if ("link".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setUrl(n2.getTextContent());
                    }
                }
                result.add(nzb);
            } catch (ParseException e) {
                LOG.info("Skipping " + nzb.getName() + " because of date error.", e);
            }
        }
    }
    THROTTLER.setThrottleForNextAction();
    return result;
}

From source file:net.sourceforge.eclipsetrader.yahoo.NewsProvider.java

private void update() {
    Object[] o = oldItems.toArray();
    for (int i = 0; i < o.length; i++) {
        ((NewsItem) o[i]).setRecent(false);
        CorePlugin.getRepository().save((NewsItem) o[i]);
    }//from  w ww .jav a2 s. c o  m
    oldItems.clear();

    Job job = new Job(Messages.NewsProvider_Name) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            IPreferenceStore store = YahooPlugin.getDefault().getPreferenceStore();

            List urls = new ArrayList();
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document document = builder.parse(FileLocator.openStream(YahooPlugin.getDefault().getBundle(),
                        new Path("categories.xml"), false)); //$NON-NLS-1$

                NodeList childNodes = document.getFirstChild().getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node node = childNodes.item(i);
                    String nodeName = node.getNodeName();
                    if (nodeName.equalsIgnoreCase("category")) //$NON-NLS-1$
                    {
                        String id = (node).getAttributes().getNamedItem("id").getNodeValue(); //$NON-NLS-1$

                        NodeList list = node.getChildNodes();
                        for (int x = 0; x < list.getLength(); x++) {
                            Node item = list.item(x);
                            nodeName = item.getNodeName();
                            Node value = item.getFirstChild();
                            if (value != null) {
                                if (nodeName.equalsIgnoreCase("url")) //$NON-NLS-1$
                                {
                                    if (store.getBoolean(id))
                                        urls.add(value.getNodeValue());
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e, e);
            }

            List securities = CorePlugin.getRepository().allSecurities();
            monitor.beginTask(Messages.NewsProvider_TaskName, securities.size() + urls.size());
            log.info("Start fetching Yahoo! News"); //$NON-NLS-1$

            for (Iterator iter = securities.iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                try {
                    String url = "http://finance.yahoo.com/rss/headline?s=" + security.getCode().toLowerCase(); //$NON-NLS-1$
                    monitor.subTask(url);
                    update(new URL(url), security);
                } catch (Exception e) {
                    log.error(e, e);
                }
                monitor.worked(1);
            }
            for (Iterator iter = urls.iterator(); iter.hasNext();) {
                String url = (String) iter.next();
                try {
                    monitor.subTask(url);
                    update(new URL(url));
                } catch (Exception e) {
                    log.error(e, e);
                }
                monitor.worked(1);
            }

            monitor.done();
            return Status.OK_STATUS;
        }
    };
    job.setUser(false);
    job.schedule();
}

From source file:net.sourceforge.eclipsetrader.news.providers.RSSNewsProvider.java

private void update() {
    Object[] o = oldItems.toArray();
    for (int i = 0; i < o.length; i++) {
        ((NewsItem) o[i]).setRecent(false);
        CorePlugin.getRepository().save((NewsItem) o[i]);
    }/*from ww  w.java 2 s.c om*/
    oldItems.clear();

    Job job = new Job(Messages.RSSNewsProvider_JobName) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            File file = new File(Platform.getLocation().toFile(), "rss.xml"); //$NON-NLS-1$
            if (file.exists() == true) {
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document document = builder.parse(file);

                    Node firstNode = document.getFirstChild();

                    NodeList childNodes = firstNode.getChildNodes();
                    monitor.beginTask(Messages.RSSNewsProvider_TaskName, childNodes.getLength());
                    log.info("Start fetching RSS News"); //$NON-NLS-1$

                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node item = childNodes.item(i);
                        String nodeName = item.getNodeName();
                        if (nodeName.equalsIgnoreCase("source")) //$NON-NLS-1$
                            update(new URL(item.getFirstChild().getNodeValue()),
                                    item.getAttributes().getNamedItem("name").getNodeValue()); //$NON-NLS-1$

                        monitor.worked(1);
                    }
                } catch (Exception e) {
                    log.error(e, e);
                }
            }

            monitor.done();
            return Status.OK_STATUS;
        }
    };
    job.setUser(false);
    job.schedule();
}