Example usage for org.w3c.dom Document getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:it.cicolella.phwswethv2.ProgettiHwSwEthv2.java

private void evaluateDiffs(Document doc, Board board) {
    //parses xml//  www.ja  v  a2s .  c  om
    if (doc != null && board != null) {
        Node n = doc.getFirstChild();
        if (board.getMonitorRelay().equalsIgnoreCase("true")) {
            valueTag(doc, board, board.getRelayNumber(), board.getLedTag(), 0);
        }
        if (board.getMonitorDigitalInput().equalsIgnoreCase("true")) {
            valueTag(doc, board, board.getDigitalInputNumber(), board.getDigitalInputTag(), 0);
        }
        if (board.getMonitorAnalogInput().equalsIgnoreCase("true")) {
            valueTag(doc, board, board.getAnalogInputNumber(), board.getAnalogInputTag(), 0);
        }
    }
}

From source file:com.marklogic.client.test.SPARQLManagerTest.java

@Test
public void testDescribe() {
    // verify base has expected effect
    String relativeConstruct = "DESCRIBE <http://example.org/s1>";
    SPARQLQueryDefinition qdef = smgr.newQueryDefinition(relativeConstruct);
    Document rdf = smgr.executeConstruct(qdef, new DOMHandle()).get();

    Node description = rdf.getFirstChild().getFirstChild();
    assertNotNull(description.getAttributes());
    assertEquals("subject", "http://example.org/s1", description.getAttributes().item(0).getTextContent());
    assertNotNull(description.getFirstChild());
    assertEquals("predicate", "p1", description.getFirstChild().getNodeName());
    assertEquals("predicate namespace", "http://example.org/", description.getFirstChild().getNamespaceURI());
    NamedNodeMap attrs = description.getFirstChild().getAttributes();
    assertNotNull(attrs);//from w w w .ja va  2  s  .  c o m
    assertNotNull(attrs.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource"));
    assertEquals("object", "http://example.org/o1",
            attrs.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource").getTextContent());
}

From source file:com.waitwha.nessus.server.Server.java

/**
 * Executes the given HttpPost using a HttpClient. If 200 OK is returned, 
 * we will parse the contents and return a ServerReply implementation.
 * /*from  w  w w  .  java 2s . c  o  m*/
 * @param post   HttpPost to execute.
 * @return   ServerReply
 */
public ServerReply getReply(HttpPost post) {
    ServerReply reply = null;
    HttpClient client = this.getClient();

    try {
        log.finest(String.format("[%s] Executing POST.", post.getURI()));
        HttpResponse resp = client.execute(post);

        try {
            HttpEntity entity = resp.getEntity();

            if (resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = entity.getContent();
                log.finest(String.format("[%s] Received HTTP code %d: %dbytes (%s)", post.getURI(),
                        resp.getStatusLine().getStatusCode(), entity.getContentLength(),
                        entity.getContentType().getValue()));

                Document document = this.builder.parse(in);
                Element replyElement = (Element) document.getFirstChild();
                Element contents = ElementUtils.getFirstElementByName(replyElement, "contents");

                /*
                 * Test the first element found within the element 'contents'. If the
                 * element's name is 'token', then this is a LoginReply. However, if the
                 * name of the element is 'reports', this will mean this is a ReportListReply.
                 * 
                 */
                Element firstElement = (Element) contents.getFirstChild();
                if (firstElement == null)
                    reply = new ErrorReply(replyElement);

                else if (firstElement.getTagName().equals("reports"))
                    reply = new ReportListReply(replyElement);

                else
                    reply = new LoginReply(replyElement);

                log.finest(String.format("[%s] Parsed XML succcessfully: %s", post.getURI(),
                        reply.getClass().getName()));

            } else {
                log.warning(String.format("[%s] Received HTTP code %d. Skipping parsing of content.",
                        post.getURI(), resp.getStatusLine().getStatusCode()));
                EntityUtils.consume(entity);
            }

        } catch (IOException | SAXException | ElementNotFoundException e) {
            log.warning(String.format("Could read/parse reply from server %s: %s %s", this.url,
                    e.getClass().getName(), e.getMessage()));

        }

    } catch (IOException e) {
        log.warning(String.format("Could not connect to server %s: %s", this.url, e.getMessage()));

    }

    return reply;
}

From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java

CurrencyConverter() {
    File file = new File(Platform.getLocation().toFile(), "currencies.xml"); //$NON-NLS-1$
    if (file.exists() == true) {
        try {//from   w w w .j  a v a 2 s .  c om
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);

            Node firstNode = document.getFirstChild();

            NodeList childNodes = firstNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);
                String nodeName = item.getNodeName();

                if (nodeName.equalsIgnoreCase("currency")) //$NON-NLS-1$
                {
                    Node valueNode = item.getFirstChild();
                    if (valueNode != null)
                        currencies.add(valueNode.getNodeValue());
                } else if (nodeName.equalsIgnoreCase("conversion")) //$NON-NLS-1$
                {
                    String symbol = (item).getAttributes().getNamedItem("symbol").getNodeValue(); //$NON-NLS-1$

                    Node valueNode = null;
                    if ((item).getAttributes().getNamedItem("ratio") != null) //$NON-NLS-1$
                        valueNode = (item).getAttributes().getNamedItem("ratio"); //$NON-NLS-1$
                    if (valueNode == null)
                        valueNode = item.getFirstChild();
                    if (valueNode != null) {
                        Double value = new Double(Double.parseDouble(valueNode.getNodeValue()));
                        map.put(symbol, value);
                    }
                    readHistory(symbol, item.getChildNodes());
                }
            }
        } catch (Exception e) {
            logger.error(e, e);
        }
    }
}

From source file:com.cloud.hypervisor.kvm.resource.wrapper.LibvirtMigrateCommandWrapper.java

private String replaceStorage(String xmlDesc, Map<String, MigrateCommand.MigrateDiskInfo> migrateStorage)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    InputStream in = IOUtils.toInputStream(xmlDesc);

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(in);

    // Get the root element
    Node domainNode = doc.getFirstChild();

    NodeList domainChildNodes = domainNode.getChildNodes();

    for (int i = 0; i < domainChildNodes.getLength(); i++) {
        Node domainChildNode = domainChildNodes.item(i);

        if ("devices".equals(domainChildNode.getNodeName())) {
            NodeList devicesChildNodes = domainChildNode.getChildNodes();

            for (int x = 0; x < devicesChildNodes.getLength(); x++) {
                Node deviceChildNode = devicesChildNodes.item(x);

                if ("disk".equals(deviceChildNode.getNodeName())) {
                    Node diskNode = deviceChildNode;

                    String sourceFileDevText = getSourceFileDevText(diskNode);

                    String path = getPathFromSourceFileDevText(migrateStorage.keySet(), sourceFileDevText);

                    if (path != null) {
                        MigrateCommand.MigrateDiskInfo migrateDiskInfo = migrateStorage.remove(path);

                        NamedNodeMap diskNodeAttributes = diskNode.getAttributes();
                        Node diskNodeAttribute = diskNodeAttributes.getNamedItem("type");

                        diskNodeAttribute.setTextContent(migrateDiskInfo.getDiskType().toString());

                        NodeList diskChildNodes = diskNode.getChildNodes();

                        for (int z = 0; z < diskChildNodes.getLength(); z++) {
                            Node diskChildNode = diskChildNodes.item(z);

                            if ("driver".equals(diskChildNode.getNodeName())) {
                                Node driverNode = diskChildNode;

                                NamedNodeMap driverNodeAttributes = driverNode.getAttributes();
                                Node driverNodeAttribute = driverNodeAttributes.getNamedItem("type");

                                driverNodeAttribute.setTextContent(migrateDiskInfo.getDriverType().toString());
                            } else if ("source".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);

                                Element newChildSourceNode = doc.createElement("source");

                                newChildSourceNode.setAttribute(migrateDiskInfo.getSource().toString(),
                                        migrateDiskInfo.getSourceText());

                                diskNode.appendChild(newChildSourceNode);
                            } else if ("auth".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);
                            } else if ("iotune".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);
                            }/*w  w  w  .  j  a  v  a2 s  .c  o m*/
                        }
                    }
                }
            }
        }
    }

    if (!migrateStorage.isEmpty()) {
        throw new CloudRuntimeException(
                "Disk info was passed into LibvirtMigrateCommandWrapper.replaceStorage that was not used.");
    }

    return getXml(doc);
}

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 .  ja va 2 s. c om
    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:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.java

private void evaluateDiffs(Document doc, Board board) {
    //parses xml/*w  w w.j  ava2s. c o m*/
    if (doc != null && board != null) {
        Node n = doc.getFirstChild();
        if (board.getMonitorRelay().equalsIgnoreCase("true")) {
            valueTag(doc, board, board.getRelayNumber(), board.getLedTag(), 0);
        }
        if (board.getMonitorTemperature().equalsIgnoreCase("true")) {
            valueTag(doc, board, board.getTemperatureNumber(), board.getTempTag(), 0);
        }
        if (board.getMonitorDigitalInput().equalsIgnoreCase("true")) {
            valueTag(doc, board, board.getDigitalInputNumber(), board.getDigitalInputTag(), 0);
        }
        if (board.getMonitorAnalogInput().equalsIgnoreCase("true")) {
            valueTag(doc, board, board.getAnalogInputNumber(), board.getAnalogInputTag(), 0);
        }
    }
}

From source file:com.l2jfree.gameserver.datatables.SummonItemsData.java

private SummonItemsData() {
    _summonitems = new FastMap<Integer, L2SummonItem>();
    Document doc = null;
    File file = new File(Config.DATAPACK_ROOT, "data/summon_items.xml");

    try {/*from w w  w. ja  v  a  2 s  .co m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setIgnoringComments(true);
        doc = factory.newDocumentBuilder().parse(file);

        int itemID = 0, npcID = 0;
        byte summonType = 0;
        Node a;
        for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("list".equalsIgnoreCase(n.getNodeName())) {
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    if ("item".equalsIgnoreCase(d.getNodeName())) {
                        a = d.getAttributes().getNamedItem("id");
                        if (a == null)
                            throw new Exception("Error in summon item defenition!");
                        itemID = Integer.parseInt(a.getNodeValue());

                        for (Node e = d.getFirstChild(); e != null; e = e.getNextSibling()) {
                            if ("npcId".equalsIgnoreCase(e.getNodeName())) {
                                a = e.getAttributes().getNamedItem("val");
                                if (a == null)
                                    throw new Exception(
                                            "Not defined npc id for summon item id=" + itemID + "!");
                                npcID = Integer.parseInt(a.getNodeValue());
                            } else if ("summonType".equalsIgnoreCase(e.getNodeName())) {
                                a = e.getAttributes().getNamedItem("val");
                                if (a == null)
                                    throw new Exception(
                                            "Not defined summon type for summon item id=" + itemID + "!");
                                summonType = Byte.parseByte(a.getNodeValue());
                            }
                        }
                        L2SummonItem summonitem = new L2SummonItem(itemID, npcID, summonType);
                        _summonitems.put(itemID, summonitem);
                    }
                }
            }
        }
        _summonItemIds = new int[_summonitems.size()];
        int i = 0;
        for (int itemId : _summonitems.keySet())
            _summonItemIds[i++] = itemId;
    } catch (IOException e) {
        _log.warn("SummonItemsData: Can not find " + file.getAbsolutePath() + " !", e);
    } catch (Exception e) {
        _log.warn("SummonItemsData: Error while parsing " + file.getAbsolutePath() + " !", e);
    }
    _log.info("SummonItemsData: Loaded " + _summonitems.size() + " Summon Items from " + file.getName());
}

From source file:com.anite.zebra.ext.xmlloader.XMLLoadProcess.java

/**
 * loads an XML process definition/*from w  ww . j ava2 s.co m*/
 * 
 * @param xmlFile
 *            xml file to load
 * @param processDefClass
 *            class to use for ProcessDefinition (IProcessDef)
 * @param taskDefClass
 *            class to use for TaskDefinition (ITaskDef)
 * @return an instance of the processDefClass with all the Process information loaded into it
 * @throws Exception
 */
public IProcessVersions loadFromFile(File xmlFile) throws Exception {
    log.debug("Processing XML in " + xmlFile.getName());

    checkProperties();

    Document doc = readDocument(xmlFile);
    Node root = doc.getFirstChild();

    try {
        return processHeader(root);
    } catch (Exception e) {
        log.error(e);
        e.printStackTrace();
        throw e;
    }

}

From source file:com.l2jfree.gameserver.instancemanager.CursedWeaponsManager.java

private final void load() {
    Connection con = null;/*from  w w w  .j  a  v a 2 s.  c  o  m*/

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setIgnoringComments(true);

        File file = new File(Config.DATAPACK_ROOT, "data/cursedWeapons.xml");
        if (!file.exists())
            throw new IOException();

        Document doc = factory.newDocumentBuilder().parse(file);

        for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("list".equalsIgnoreCase(n.getNodeName())) {
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    if ("item".equalsIgnoreCase(d.getNodeName())) {
                        NamedNodeMap attrs = d.getAttributes();
                        int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue());
                        int skillId = Integer.parseInt(attrs.getNamedItem("skillId").getNodeValue());
                        String name = attrs.getNamedItem("name").getNodeValue();

                        CursedWeapon cw = new CursedWeapon(id, skillId, name);

                        int val;
                        for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) {
                            if ("dropRate".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDropRate(val);
                            } else if ("duration".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDuration(val);
                            } else if ("durationLost".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDurationLost(val);
                            } else if ("disapearChance".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setDisapearChance(val);
                            } else if ("stageKills".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setStageKills(val);
                            } else if ("transformId".equalsIgnoreCase(cd.getNodeName())) {
                                attrs = cd.getAttributes();
                                val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue());
                                cw.setTransformId(val);
                            }
                        }

                        // Store cursed weapon
                        _cursedWeapons.put(id, cw);
                    }
                }
            }
        }

        // Retrieve the L2Player from the characters table of the database
        con = L2DatabaseFactory.getInstance().getConnection();

        if (Config.ALLOW_CURSED_WEAPONS) {
            PreparedStatement statement = con.prepareStatement(
                    "SELECT itemId, charId, playerKarma, playerPkKills, nbKills, endTime FROM cursed_weapons");
            ResultSet rset = statement.executeQuery();

            while (rset.next()) {
                int itemId = rset.getInt("itemId");
                int playerId = rset.getInt("charId");
                int playerKarma = rset.getInt("playerKarma");
                int playerPkKills = rset.getInt("playerPkKills");
                int nbKills = rset.getInt("nbKills");
                long endTime = rset.getLong("endTime");

                CursedWeapon cw = _cursedWeapons.get(itemId);
                cw.setPlayerId(playerId);
                cw.setPlayerKarma(playerKarma);
                cw.setPlayerPkKills(playerPkKills);
                cw.setNbKills(nbKills);
                cw.setEndTime(endTime);
                cw.reActivate();
            }

            rset.close();
            statement.close();
        } else {
            PreparedStatement statement = con.prepareStatement("TRUNCATE TABLE cursed_weapons");
            ResultSet rset = statement.executeQuery();
            rset.close();
            statement.close();
        }

        //L2DatabaseFactory.close(con);

        // Retrieve the L2Player from the characters table of the database
        //con = L2DatabaseFactory.getInstance().getConnection(con);

        for (CursedWeapon cw : _cursedWeapons.values()) {
            if (cw.isActivated())
                continue;

            // Do an item check to be sure that the cursed weapon isn't hold by someone
            int itemId = cw.getItemId();
            try {
                PreparedStatement statement = con
                        .prepareStatement("SELECT owner_id FROM items WHERE item_id=?");
                statement.setInt(1, itemId);
                ResultSet rset = statement.executeQuery();

                if (rset.next()) {
                    // A player has the cursed weapon in his inventory ...
                    int playerId = rset.getInt("owner_id");
                    _log.info("PROBLEM : Player " + playerId + " owns the cursed weapon " + itemId
                            + " but he shouldn't.");

                    // Delete the item
                    PreparedStatement statement2 = con
                            .prepareStatement("DELETE FROM items WHERE owner_id=? AND item_id=?");
                    statement2.setInt(1, playerId);
                    statement2.setInt(2, itemId);
                    if (statement2.executeUpdate() != 1) {
                        _log.warn("Error while deleting cursed weapon " + itemId + " from userId " + playerId);
                    }
                    statement2.close();

                    // Delete the skill
                    /*
                    statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=? AND skill_id=");
                    statement.setInt(1, playerId);
                    statement.setInt(2, cw.getSkillId());
                    if (statement.executeUpdate() != 1)
                    {
                        _log.warn("Error while deleting cursed weapon "+itemId+" skill from userId "+playerId);
                    }
                    */
                    // Restore the player's old karma and pk count
                    statement2 = con
                            .prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId = ?");
                    statement2.setInt(1, cw.getPlayerKarma());
                    statement2.setInt(2, cw.getPlayerPkKills());
                    statement2.setInt(3, playerId);
                    if (statement2.executeUpdate() != 1) {
                        _log.warn("Error while updating karma & pkkills for charId " + cw.getPlayerId());
                    }
                    statement2.close();
                    // clean up the cursedweapons table.
                    removeFromDb(itemId);
                }
                rset.close();
                statement.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
        }
    } catch (Exception e) {
        _log.warn("Could not load CursedWeapons data: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    _log.info("CursedWeaponsManager: loaded " + _cursedWeapons.size() + " cursed weapon(s).");
}